简体   繁体   中英

Array of associative arrays to associative array, indexed on the value of a key

An array of associative arrays must be converted to an associative array whose keys are the values of one key of those associative arrays. For example, this array:

$source = array(array("key" => "a", "value" => "1"),
                array("key" => "b", "value" => "2"),
                array("key" => "a", "value" => "3"),
                array("key" => "b", "value" => "4"));

must be converted to the following associative array, based on the values of the key "key" :

$dest = array("a" => array(array("key" => "a", "value" => "1"),
                           array("key" => "a", "value" => "3")),
              "b" => array(array("key" => "b", "value" => "2"),
                           array("key" => "b", "value" => "4")));

This is what I would do:

$dest = array();
foreach($source as $elem) {
    $key = $elem["key"];
    if(!array_key_exists($key, $dest)){
        $dest[$key] = array();
    }
    array_push($dest[$key], $elem);
}

Is there a more idiomatic way?

You can do it using simple foreach stuff:

$source_arr = array(array("key" => "a", "value" => "1"),
                array("key" => "b", "value" => "2"),
                array("key" => "a", "value" => "3"),
                array("key" => "b", "value" => "4"));

$destination_arr = array();
foreach ($destination_arr as $k => $v)
{
  $key = $v['key'];
  $destination_arr[$key][$k] = array('key' => $v['key'], 'value' => $v['value']);
}

print_r($destination_arr);

Change your to this.

    <?php
        $dest = array(array("key" => "a", "value" => "1"),
                    array("key" => "b", "value" => "2"),
                    array("key" => "a", "value" => "3"),
                    array("key" => "b", "value" => "4"));
         $result = array();
        foreach($dest as $elem) {
            $result[$elem['key']][] = ["key"=>$elem['key'],"value"=>$elem['value']];
        }
        print_r($result);
    ?>

Check this : https://eval.in/605983

Output is :

Array
(
    [a] => Array
        (
            [0] => Array
                (
                    [key] => a
                    [value] => 1
                )

            [1] => Array
                (
                    [key] => a
                    [value] => 3
                )

        )

    [b] => Array
        (
            [0] => Array
                (
                    [key] => b
                    [value] => 2
                )

            [1] => Array
                (
                    [key] => b
                    [value] => 4
                )

        )

)

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