[英]Split PHP array based on subarray values
Is there a PHP function, or other solution, that will facilitate splitting an array based on a value from it's subarrays? 是否有PHP函数或其他解决方案可帮助根据子数组中的值拆分数组?
Yes, I know I can do this with a loop! 是的,我知道我可以循环执行此操作! The question is if there's another way to do it without having loop through. 问题是是否还有另一种方法可以避免循环。
Example: 例:
Using the value of Active, turn this array... 使用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
)
)
...into this array... ...进入这个数组...
$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
)
)
... and this array. ...以及这个数组。
$array_inactive => Array
(
[1596] => Array
(
[DisplayName] => Customer 123
[Active] => 0
)
[1649] => Array
(
[DisplayName] => Fry & Leela, Inc.
[Active] => 0
)
)
You could use array_filter
: 您可以使用array_filter
:
$actives = array_filter($array_all, function ($row) {
return $row["Active"];
});
$notActives = array_filter($array_all, function ($row) {
return !$row["Active"];
});
You can also use array_reduce
as alternative, but it returns indexed arrays, so without the original keys: 您也可以使用array_reduce
作为替代,但是它返回索引数组,因此没有原始键:
list($actives, $notActives) = array_reduce($array_all, function ($result, $row) {
$result[$row["Active"]][] = $row;
return $result;
}, [[],[]]);
When using array_reduce
to also maintain keys, it becomes quite verbose: 当使用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;
}, [[],[]]
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.