phparraysmultidimensional-arraygrouping

Synchronously traverse 3 rows of a 2d array to populate a fully associative array


I am trying to figure out how to reorganize an array.. I have a multidimensional array(Ill call that original_array) and I would like to take the first array within original_array and set the values as keys in a new array. I also want to take the values of the second array in original_array and make them keys and then set the values of the third array in original_array as the values for those keys.

Here is an example of original_array:

Array ( 
       [id] => Array ( 
                      [0] => 1 
                      [1] => 3 
                     ) 
   [reward] => Array ( 
                      [0] => Movie
                      [1] => Trip
                     ) 
     [cost] => Array ( 
                      [0] => 50 
                      [1] => 200
                     ) 
      )

Basically what I would like to do is look like this:

Array ( 
       [1] => Array ( 
                     [Movie] => 50
                    )
       [3] => Array (
                     [Trip] => 200
                    )
      )

Is there a simple and elegant way to merge these like this? I have spent hours trying to figure this out using array_merge, array_merge_recursive.. etc. And have search SO far and wide for a similar questions, but I haven't found anything that does what I am after.

I was able to correctly combine the 2nd and 3rd arrays in original_array with array_combine. But, I am at a loss as how to combine that result with the 1st array's values in original_array.


Solution

  • There may be some incantation of array_*() merging functions that could produce what you're looking for, but it is far easier to just iterate over the original array's [id] sub-array and use its values to create new sub-array keys in a different output array.

    // To hold your output
    $output = array();
    
    // Iterate the original array's [id] sub-array
    foreach ($original['id'] as $idxkey => $newkey) {
      // Add a sub-array using $newkey to the output array
      $output[$newkey] = array( 
        // Using the index (not value), retrieve the corresponding reward
        // value to use as the new array key
        // and corresponding cost to use as the new subarray value
        $original['reward'][$idxkey] => $original['cost'][$idxkey]
      );
    }
    

    Here is a demonstration: https://3v4l.org/2pac3