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

PHP如何从现有多维数组中提取指定元素创建新多维数组

这是PHP里很常见的数组提取需求,我给你整理了几种实用的实现方式,你可以根据自己的PHP版本和场景选择:

方法1:foreach循环(最直观易读)

这是最基础也最不容易出错的方式,适合所有PHP版本,还能灵活处理原数组可能缺失指定键的情况:

$results = array(
 0 => array( 'fruit' => 'apple', 'colour' => 'green', 'amount' => 50 ),
 1 => array( 'fruit' => 'orange', 'colour' => 'orange', 'amount' => 25 ),
 2 => array( 'fruit' => 'banana', 'colour' => 'yellow', 'amount' => 7 )
);

$newarray = [];
// 定义需要保留的键
$requiredKeys = ['fruit', 'amount'];

foreach ($results as $item) {
    $filteredItem = [];
    foreach ($requiredKeys as $key) {
        // 先检查键是否存在,避免出现Notice错误
        if (isset($item[$key])) {
            $filteredItem[$key] = $item[$key];
        }
    }
    $newarray[] = $filteredItem;
}

print_r($newarray);
方法2:array_map + 匿名函数(PHP 5.3+)

如果你的PHP版本在5.3及以上,用array_map配合匿名函数能让代码更紧凑:

$results = array(
 0 => array( 'fruit' => 'apple', 'colour' => 'green', 'amount' => 50 ),
 1 => array( 'fruit' => 'orange', 'colour' => 'orange', 'amount' => 25 ),
 2 => array( 'fruit' => 'banana', 'colour' => 'yellow', 'amount' => 7 )
);

$newarray = array_map(function($item) {
    // 直接返回需要的键值对
    return [
        'fruit' => $item['fruit'],
        'amount' => $item['amount']
    ];
}, $results);

print_r($newarray);

如果担心原数组里可能缺少指定键,可以用PHP 7+的空合并运算符做容错处理:

$newarray = array_map(function($item) {
    return [
        'fruit' => $item['fruit'] ?? null,
        'amount' => $item['amount'] ?? null
    ];
}, $results);
方法3:array_intersect_key 批量筛选(适合多键场景)

如果需要保留的键比较多,用array_intersect_key可以批量筛选,不用逐个写键名:

$results = array(
 0 => array( 'fruit' => 'apple', 'colour' => 'green', 'amount' => 50 ),
 1 => array( 'fruit' => 'orange', 'colour' => 'orange', 'amount' => 25 ),
 2 => array( 'fruit' => 'banana', 'colour' => 'yellow', 'amount' => 7 )
);

// 把需要保留的键转成键名数组(值可以随便,只要存在就行)
$allowedKeys = array_flip(['fruit', 'amount']);

$newarray = array_map(function($item) use ($allowedKeys) {
    // 只保留两个数组中键名相同的元素
    return array_intersect_key($item, $allowedKeys);
}, $results);

print_r($newarray);

这种方式的好处是后续要修改保留的键时,只需要调整$allowedKeys数组即可,不用改动处理逻辑。

方法4:箭头函数(PHP 7.4+)

如果你的项目已经升级到PHP 7.4及以上,箭头函数能让代码变得非常简洁:

$results = array(
 0 => array( 'fruit' => 'apple', 'colour' => 'green', 'amount' => 50 ),
 1 => array( 'fruit' => 'orange', 'colour' => 'orange', 'amount' => 25 ),
 2 => array( 'fruit' => 'banana', 'colour' => 'yellow', 'amount' => 7 )
);

$newarray = array_map(fn($item) => ['fruit' => $item['fruit'], 'amount' => $item['amount']], $results);

print_r($newarray);

同样,要做容错的话,直接加上空合并运算符就行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:11:06