提问人:Eli 提问时间:6/28/2016 更新时间:6/28/2016 访问量:910
基于子数组值拆分 PHP 数组
Split PHP array based on subarray values
问:
是否有 PHP 函数或其他解决方案可以促进根据其子数组中的值拆分数组?
是的,我知道我可以通过循环来做到这一点!问题是是否有另一种方法可以在不循环的情况下做到这一点。
例:
使用 Active 的值,将此数组...
$array_all => Array
(
[126] => Array
(
[DisplayName] => Customer ABC
[Active] => 1
)
[1596] => Array
(
[DisplayName] => Customer 123
[Active] => 0
)
[1648] => Array
(
[DisplayName] => John Q Sample
[Active] => 1
)
[1649] => Array
(
[DisplayName] => Fry & Leela, Inc.
[Active] => 0
)
[1571] => Array
(
[DisplayName] => Class Action: Redshirts vs. UFP
[Active] => 1
)
)
...进入这个数组...
$array_active => Array
(
[126] => Array
(
[DisplayName] => Customer ABC
[Active] => 1
)
[1648] => Array
(
[DisplayName] => John Q Sample
[Active] => 1
)
[1571] => Array
(
[DisplayName] => Class Action: Redshirts vs. UFP
[Active] => 1
)
)
...和这个数组。
$array_inactive => Array
(
[1596] => Array
(
[DisplayName] => Customer 123
[Active] => 0
)
[1649] => Array
(
[DisplayName] => Fry & Leela, Inc.
[Active] => 0
)
)
答:
7赞
trincot
6/28/2016
#1
您可以使用array_filter
:
$actives = array_filter($array_all, function ($row) {
return $row["Active"];
});
$notActives = array_filter($array_all, function ($row) {
return !$row["Active"];
});
您也可以使用 array_reduce
作为替代,但它返回索引数组,因此没有原始键:
list($actives, $notActives) = array_reduce($array_all, function ($result, $row) {
$result[$row["Active"]][] = $row;
return $result;
}, [[],[]]);
当用于维护密钥时,它变得非常冗长:array_reduce
list($actives, $notActives) = array_reduce(array_keys($array_all),
function ($result, $key) use ($array_all) {
$result[$array_all[$key]["Active"]][$key] = $array_all[$key];
return $result;
}, [[],[]]
);
评论
array_filter
或?array_reduce