phparraysmultidimensional-arraytranspose

Arrange PHP Multidimensional Array By Inner Index


How to arrange this array by last inner index ( 0, 1, 2 ) and get the value of the last inner index as the value of each second index:

Array
(
    [text] => Array
        (
            [grid] => Array
                (
                    [0] => 3
                    [1] => 4
                    [2] => 5
                )

            [image] => Array
                (
                    [0] => 
                    [1] => 
                    [2] => 
                )

            [align] => Array
                (
                    [0] => left
                    [1] => right
                    [2] => left
                )

            [title] => Array
                (
                    [0] => 
                    [1] => 
                    [2] => 
                )

            [content] => Array
                (
                    [0] => 
                    [1] => 
                    [2] => 
                )

        )

)

And have the results as below:

Array
(
    [text] => Array
        (
            [0] => Array
                (
                    [grid] => 3
                    [image] => 
                    [align] => left
                    [title] => 
                    [content] => 
                )

            [1] => Array
                (
                    [grid] => 4
                    [image] => 
                    [align] => right
                    [title] => 
                    [content] => 
                )

            [2] => Array
                (
                    [grid] => 5
                    [image] => 
                    [align] => left
                    [title] => 
                    [content] => 
                )

        )

)

Solution

  • This will do the work

    function restructure($arr){
        $newArr = array();
        foreach($arr as $k => $v){
            foreach($v as $k1 => $v1){
                foreach($v1 as $k2 => $v2){
                    $newArr[$k][$k2][$k1] = $v2; 
                }
            }
        }
        return $newArr;
    }