仅在php中使用数组函数从多维数组获取具有特定条件的特定列 [英] get specific column with specific condition from multidimensional array using array function only in php
问题描述
我只想使用数组函数从多维数组中获得索引为 0,1,2 的具有特定条件的特定键.
i want to get specific key with specific condition with indexing 0,1,2 from multidimensional array using array function only.
正在使用forloop,但是我希望它使用数组函数进行代码优化
using forloop it is getting but i want it using array function for code optimization
我的输入代码如下:
Array
(
[0] => Array
(
[device_token] => 1324
[device_type] => 0
)
[1] => Array
(
[device_token] => 2546
[device_type] => 1
)
[2] => Array
(
[device_token] => 13241
[device_type] => 0
)
[3] => Array
(
[device_token] => 12345
[device_type] => 1
)
)
并且我只希望具有 device_type = 0 且具有以下格式的device_token:
and i want only device_token which have device_type=0 with following format like :
Array
(
[0] => 1324,
[1] => 13241,
)
我正在尝试以下代码:
$ios_token = array_map(function($r) {
return $r['device_token'];
}
这给了我所有的设备令牌.
this give me device token of all.
推荐答案
array_filter应该为您做到:
array_filter should do it for you :
$ios_token = array_filter($myArray, function($item) {
return $item['device_type'] == 0;
});
迭代每个值,如果回调函数返回true,则返回数组的当前值.
It iterates over each value and if the callback function returns true, the current value of the array is returned.
然后,您可以像执行操作一样在array_map函数中传递变量:
Then you could pass your variable in an array_map function like you did :
$ios_token = array_map(function($item){
return $item['device_token'];
}, $ios_token);
如果要对所有内容进行分组:
And if you want to group everything :
$ios_token = array_map(function($item){
return $item['device_token'];
}, array_filter($myArray,
function($item) {
return $item['device_type'] == 0;
}
));
这篇关于仅在php中使用数组函数从多维数组获取具有特定条件的特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!