PHP如何筛选包含指定id值的完整子数组?
筛选指定ID的数组子项
完全可以实现,下面是几种PHP的实现方式,都能得到你需要的结果:
方法一:基础循环遍历
这种方法逻辑直观,找到目标ID后立即停止遍历,效率较高:
// 原始数组 $items = [ ['id' => 1, 'item_name' => 'Oilspill', 'requests_count' => 0, 'item_information' => 'Just some spilled oil'], ['id' => 2, 'item_name' => 'Fan', 'requests_count' => 0, 'item_information' => 'Standart fan'], ['id' => 3, 'item_name' => 'Green candle', 'requests_count' => 0, 'item_information' => 'Smells like moss'], ['id' => 4, 'item_name' => 'Yin Yang', 'requests_count' => 0, 'item_information' => 'Ancient Chinese symbol'], ]; $targetId = 2; $result = null; // 遍历数组匹配目标ID foreach ($items as $key => $item) { if ($item['id'] === $targetId) { $result = [$key => $item]; break; } } // 输出结果 echo "<pre>"; print_r($result); echo "</pre>";
执行后输出:
Array ( [1] => Array ( [id] => 2 [item_name] => Fan [requests_count] => 0 [item_information] => Standart fan ) )
方法二:使用array_filter函数(保留原键)
利用PHP内置函数实现,适合更简洁的代码写法:
$targetId = 2; $result = array_filter($items, function($item) use ($targetId) { return $item['id'] === $targetId; }, ARRAY_FILTER_USE_BOTH); echo "<pre>"; print_r($result); echo "</pre>";
方法三:PHP 7.4+ 箭头函数简化版
如果你的PHP版本在7.4及以上,可以用箭头函数让代码更紧凑:
$targetId = 2; $result = array_filter($items, fn($item) => $item['id'] === $targetId, ARRAY_FILTER_USE_BOTH); echo "<pre>"; print_r($result); echo "</pre>";
注意:如果不需要保留原数组的键(比如不需要
[1]这个索引),去掉ARRAY_FILTER_USE_BOTH参数即可。
内容的提问来源于stack exchange,提问作者IloveMyCats
相关产品推荐
相关产品推荐

