是否有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
)
)
答案 0 :(得分:7)
您可以使用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;
}, [[],[]]
);