You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何移除数组中的子数组,保留原数组的键与元素

解决PHP数组移除子数组并提取键/值的问题

你可以通过遍历数组并判断元素类型的方式,将原数组转换为目标格式。以下是两种实用的实现方案:

方案一:foreach循环遍历(直观易懂)

$arr = [
  "4",
  "10" => [
    ["id" => "standard", "name" => "Standard"],
    ["id" => "standard_2.0", "name" => "Standard 2.0"]
  ],
  "11" => [
    ["id" => "gold", "name" => "Gold"],
    ["id" => "gold_2.0", "name" => "Gold 2.0"]
  ],
];

$result = [];
foreach ($arr as $key => $value) {
    // 判断当前元素是否为子数组
    if (is_array($value)) {
        // 若是子数组,将键转为字符串后加入结果
        $result[] = (string)$key;
    } else {
        // 若不是子数组,直接保留原元素值
        $result[] = $value;
    }
}

// 输出结果:Array ( [0] => 4 [1] => 10 [2] => 11 )
print_r($result);

方案二:array_reduce函数(简洁写法)

利用array_reduce结合数组键遍历,实现更紧凑的代码:

$arr = [
  "4",
  "10" => [
    ["id" => "standard", "name" => "Standard"],
    ["id" => "standard_2.0", "name" => "Standard 2.0"]
  ],
  "11" => [
    ["id" => "gold", "name" => "Gold"],
    ["id" => "gold_2.0", "name" => "Gold 2.0"]
  ],
];

$result = array_reduce(
    array_keys($arr),
    function($carry, $key) use ($arr) {
        $item = is_array($arr[$key]) ? (string)$key : $arr[$key];
        $carry[] = $item;
        return $carry;
    },
    []
);

// 输出结果同上
print_r($result);

核心逻辑说明

  • 遍历原数组的每个键值对
  • 当值是子数组时,提取对应的键(转为字符串保证类型统一)
  • 当值是普通字符串时,直接保留该值
  • 最终将所有收集到的元素组合成新的索引数组

内容的提问来源于stack exchange,提问作者Hector

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 17:42:24