Search code examples
phparraysmultidimensional-arraytranspose

How to re-arranging an array


I am having and issue to rearrange a array, i try most of them.. try to use array_merge, foreach, forloop, while loop etc. but no luck

My concept is not clear i need your help to get an idea how I can change array as per my requirements, Its batter if you give me the concept idea only, i don't required code i try my self first to code it.

Here is the array

   Array
    (
      [links] => Array
             (
     [song_name] => Array
             (
                 [0] => AA
                 [1] => BB
                 [2] => CC
                 .....
             )

              [singer_name] => Array
             (
                 [0] => AA
                 [1] => BB
                 [2] => CC
                 .....
             )

              [song_url_320] => Array
             (
                 [0] => AA
                 [1] => BB
                 [2] => CC
                 .....
             )

              [song_url_128] => Array
             (
                 [0] => AA
                 [1] => BB
                 [2] => CC
                 .....
             )
        )

     )

I Need to change array like this:

Array
(
    [links] => Array
        (
            [0] => Array
                (
                    [song_name] => AA
                    [singer_name] => AA
                    [song_url_320] => AA
                    [song_url_128] => AA
                        .....
                )
         [1] => Array
                (
                    [song_name] => BB
                    [singer_name] => BB
                    [song_url_320] => BB
                    [song_url_128] => BB
                        .....
                )
         [2] => Array
                (
                    [song_name] => CC
                    [singer_name] => CC
                    [song_url_320] => CC
                    [song_url_128] => CC
                        .....
                )
        )
)

Solution

  • Idea: loop through all items and combine them into another array

    Here is sample code:

    $inputarray = array(...);
    
    $outputarray = array('links' => array());
    foreach ($inputarray['links'] as $k => $v)
        foreach ($v as $k2 => $v2) {
            $outputarray['links'][$k2][$k] = $v2;
        }