简体   繁体   中英

Split PHP Array by Key=>Value

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",...],
    ],
];

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.

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM