Search code examples
phparraysarray-mergearray-key

multidimensional array, transpositional values and merged result


I have and array $aArg with these values

array ( 0 => 'reviewed_entity', 1 => 'kiosk', )
array ( 0 => 'tripadvisor', 1 => 'tripadvisor2', )
array ( 0 => 'google', 1 => 'google2', )
array ( 0 => 'yahoo', 1 => 'yahoo2', )

I need to make it appear as below.

array ('kiosk'  =>  array ( 'tripadvisor' => 'tripadvisor2','google' => 'google2','yahoo' => 'yahoo2',));
  • Please note a few things Kiosk is the value of the [1] of first array. and it's now the parent array'
  • Other arrays have values of [0] transpose as key for [1]
  • All the arrays have been merged into one.

Thank you guys I have had sleepless nights trying to get final merge result, please share with me the fastest way to get desired results


Solution

  • Your input array doesn't seems to be correct. I thought it was like the following..

    <?php $aArg = array(
    array ( 0 => 'reviewed_entity', 1 => 'kiosk', ),
    array ( 0 => 'tripadvisor', 1 => 'tripadvisor2', ),
    array ( 0 => 'google', 1 => 'google2', ),
    array ( 0 => 'yahoo', 1 => 'yahoo2', ));
    
    
    $newArr = array($aArg[0][1] => array());
    $i = 0;
    foreach($aArg as $arr) {
      if($i) {
        $newArr[$aArg[0][1]][$arr[0]] = $arr[1];
      }
      $i ++;
    } 
    var_export($newArr);