phparraysmultidimensional-arraytranspose

Swap first level keys and second levels keys of a 2d array


I am trying to seperate some value by key.

My current array like this

Array
(
    [name] => Array
        (
            [0] => test1
            [1] => test2
        )

    [type] => Array
        (
            [0] => image/jpeg
            [1] => image/jpeg
        )

    [tmp_name] => Array
        (
            [0] => D:\xampp5\tmp\php5F43.tmp
            [1] => D:\xampp5\tmp\php5F63.tmp
        )

    [error] => Array
        (
            [0] => 0
            [1] => 0
        )

    [size] => Array
        (
            [0] => 49293
            [1] => 20286
        )

)

My expected array will be like this

Array
( 
 [0] =>(
    [name] =>  test1

    [type] =>  image/jpeg

    [tmp_name] => D:\xampp5\tmp\php5F43.tmp

    [error] => 0

    [size] =>  49293
    )

[1] =>(
    [name] =>  test2

    [type] =>  image/jpeg

    [tmp_name] => D:\xampp5\tmp\php5F63.tmp

    [error] => 0

    [size] =>  20286
    )
)

For this I tried like this

$files = array();
$i = 0;
foreach ($array as $key => $value) {
    foreach ($value as $item) {
        $files[$i][] = $item;
        // echo '["'.$key.'"] - '.$item.'<br>';
        $i++;
    }
}

But it's just increasing array index not pushing under specific key.

Please suggest what I missed here


Solution

  • Try this :

    $result = [];
    
    foreach ($array as $key => $subarray) {
        foreach ($subarray as $index => $data) {
            $result[$index][$key] = $data;
        }
    }
    

    Example here : link