[英]PHP - Get value from keys in multidimensional array
Here is my array 这是我的数组
$myArray = Array(
[63145] => Array
(
[id] => 63145
[name] => banana
[type] => fruit
)
[244340] => Array
(
[id] => 244340
[name] => apple
[type] => fruit
)
[253925] => Array
(
[id] => 253925
[name] => portato
[type] => vegetable
)
[233094] => Array
(
[id] => 233094
[name] => carrot
[type] => vegetable
));
How do i loop through this and pull out the ids of all fruits, so i kan use them in another foreach loop? 我该如何循环浏览并提取所有水果的ID,以便在另一个foreach循环中使用它们?
I have tried to look through other questions but I can't figure out how to convert the answers to my array (I know I'm a noob).. 我试图研究其他问题,但我不知道如何将答案转换为数组(我知道我是菜鸟)。
The naïve: 天真:
$fruitIds = [];
foreach ($myArray as $item) {
if ($item['type'] == 'fruit') {
$fruitIds[] = $item['id'];
}
}
The functional: 功能:
$fruitIds = array_column(
array_filter($myArray, function (array $i) { return $i['type'] == 'fruit'; }),
'id'
);
The more efficient functional: 更有效的功能:
$fruitIds = array_reduce($myArray, function (array $ids, array $i) {
return array_merge($ids, $i['type'] == 'fruit' ? [$i['id']] : []);
}, []);
You can do this using PHP's array_column
and array_filter
: 您可以使用PHP的array_column
和array_filter
做到这array_filter
:
$fruit_ids = array_column(array_filter($arr, function($item, $index) {
return $item['type'] == 'fruit';
}), 'id');
But also your array keys seem to be the same as your id values on the child arrays, so you could mix array_filter
with array_keys
: 但是,您的数组键似乎也与子数组上的id值相同,因此您可以将array_filter
与array_keys
混合使用:
$fruit_ids = array_keys(array_filter($arr, function($item, $index) {
return $item['type'] == 'fruit';
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.