Split PHP Array by Key=>Value

2019-08-27 10:28发布

I have a two dimensional array like this:

$array = [
    [..., "key"=>"key 1",...],
    [..., "key"=>"key 2",...],
    [..., "key"=>"key 2",...],
    [..., "key"=>"key 3",...],
    [..., "key"=>"key 3",...],
    [..., "key"=>"key 3",...],
];

I want a three dimensional array from this array, splitted by the same "key" value,
like this:

$array_output = [
    [
        [..., "key"=>"key 1",...],
    ],
    [
        [..., "key"=>"key 2",...],
        [..., "key"=>"key 2",...],
    ],
    [
        [..., "key"=>"key 3",...],
        [..., "key"=>"key 3",...],
        [..., "key"=>"key 3",...],
    ],
];

标签: php arrays
2条回答
可以哭但决不认输i
2楼-- · 2019-08-27 11:17

You can do that with array-reduce. Consider this example:

$arr = [];
$arr[] = array("key" => "key1", "v" => "a");
$arr[] = array("key" => "key2", "v" => "b");
$arr[] = array("key" => "key3", "v" => "c");
$arr[] = array("key" => "key2", "v" => "d");
$arr[] = array("key" => "key2", "v" => "e");

function reduceByKey($carry, $item) {
    $carry[$item["key"]][] = $item;
    return $carry;
}
$res = array_values(array_reduce($arr, "reduceByKey",[]));

Now $res will have your output. Notice that the order of the keys in $arr in not relevant.

查看更多
贪生不怕死
3楼-- · 2019-08-27 11:27

Finally, This function fulfilled my expectation:

function _group_by($array, $key) {
    $return = array();
    foreach($array as $val) {
        $return[$val->$key][] = $val;
    }
    return $return;
}
$array = _group_by($array, 'key');

However, this returns with Key Value pair, like:

[
    "key 1"=>[
        [..., "key"=>"key 1",...],
    ],
    "key 2"=>[
        [..., "key"=>"key 2",...],
        [..., "key"=>"key 2",...],
    ],
    "key 3"=>[
        [..., "key"=>"key 3",...],
        [..., "key"=>"key 3",...],
        [..., "key"=>"key 3",...],
    ],
];

but that cause no problem for me :)

查看更多
登录 后发表回答