简体   繁体   中英

Split multidimensional array into arrays

So I have a result from a form post that looks like this:

$data = [
    'id_1' => [ 
        '0' => 1,
        '1' => 2
     ],
    'id_2' => [ 
        '0' => 3,
        '1' => 4
    ],
    'id_3' => [ 
        '0' => 5,
        '1' => 6
    ]
];

What I want to achieve is to split this array into two different arrays like this:

$item_1 = [
    'id_1' => 1,
    'id_2' => 3,
    'id_3' => 5
]

$item_2 = [
    'id_1' => 2,
    'id_2' => 4,
    'id_3' => 6
]

I've tried using all of the proper array methods such as array_chunk, array_merge with loops but I can't seem to get my mind wrapped around how to achieve this. I've seen a lot of similar posts where the first keys doesn't have names like my array does (id_1, id_2, id_3). But in my case the names of the keys are crucial since they need to be set as the names of the keys in the individual arrays.

Solution without loop and just for fun:

$result = [[], []];
$keys = array_keys($data);
array_map(function($item) use(&$result, &$keys) {
    $key = array_shift($keys);
    $result[0][$key] = $item[0];
    $result[1][$key] = $item[1];
}, $data);

Just a normal foreach loop will do.

$item_1 = [];
$item_2 = [];
foreach ($data as $k => $v){
    $item_1[$k] = $v[0];
    $item_2[$k] = $v[1];
}

Hope this helps.

Much shorter than this will be hard to find:

$item1 = array_map('reset', $data);
$item2 = array_map('end', $data);

Explanation

array_map expects a callback function as its first argument. In the first line this is reset , so reset will be called on every element of $data , effectively taking the first element values of the sub arrays. array_map combines these results in a new array, keeping the original keys.

The second line does the same, but with the function end , which effectively grabs the last element's values of the sub-arrays.

The fact that both reset and end move the internal array pointer, is of no concern. The only thing that matters here is that they also return the value of the element where they put that pointer to.

Assuming that on each 'id_1' you have only 2 sets of key value pairs, the following will do what you like to achieve.

$item_1 = array();
$item_2 = array();

foreach ($data as $item) {
    $item_1 = $item[0];
    $item_2 = $item[1];
}

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