How do I invert a multidimensional array in PHP

 

Questions


Whats the easiest way to invert a multidimensional array. By invert I mean similar to array_flip.

e.g

[0][5][var_name] = data
[0][3][var_name2] = data2
[1][var_name3] = data3
[0][1][4][var_name4] = data4

inverted would be:

[var_name][0][5] = data
[var_name2][0][3] = data2
[var_name3][1] = data3
[var_name4][0][1][4] = data4

Any ideas?

 

 

————————————————-

Answer

You could store a list of the keys of all ancestors and when you hit a “leaf” use this list to create the “flipped” version.

<?php
$data = array(
  0=>array(
    5=>array('var_name' => 'data'),
    3=>array('var_name2' => 'data2'),
    1=>array(4=>array('var_name4'=>'data4'))
  ),
  1=>array('var_name3'=>'data3')
);

$result = array();
foo($data, $result);

($result['var_name'][0][5] === 'data') or die('1');
($result['var_name2'][0][3] === 'data2') or die('2');
($result['var_name3'][1] === 'data3') or die('3');
($result['var_name4'][0][1][4] === 'data4') or die('4');
echo 'ok';


function foo(array $a, array &$target, $stack=array()) {
  foreach($a as $key=>$value) {
    if ( is_array($value) ) {
      array_push($stack, $key);
      foo($value, $target, $stack);
      array_pop($stack);
    }
    else {
      $target[$key] = array();
      $tmp = &$target[$key];
      foreach( $stack as $s ) { // now it's not so stack-ish anymore :-S
        $tmp[$s] = array();
        $tmp = &$tmp[$s];
      }
      $tmp = $value;
    }
  }
}

arrays,php

[], []

Facebook Comments

Post a comment