Stfvns Stfvns - 2 months ago 28
PHP Question

Convert multi-dimensional array key value

I have array like:

$x = array(
'a' => array('aa' => array('aaa' => array(1, 2, 3))),
'b' => array('bb' => array('bbb' => array(1, 2, 3))),
);


Then, I want to modifying array to:

$y = array(
1 => array('a', 'b'),
2 => array('aa', 'bb'),
3 => array('aaa', 'bbb'),
);


Please help me!

NB: if the last array 2,1,3 will be
2->a,b; 1->aa,bb; 3->aaa,bbb

Answer

Based on what you explained, I would suggest something like this:

$x = array(
  'a' => array('aa' => array('aaa' => array(1, 2, 3))),
  'b' => array('bb' => array('bbb' => array(1, 2, 3))),
);

$y = array();
$l = array();
foreach ($x as $l[0] => $x2) {
    foreach ($x2 as $l[1] => $x3) {
        foreach ($x3 as $l[2] => $keys) {
            for ($i = 0; $i < 3; $i++) {
                if (isset($y[$keys[$i]])) {
                    $y[$keys[$i]][] = $l[$i];
                } else {
                    $y[$keys[$i]] = array($l[$i]);
                }
            }
        }
    }
}

But please note that this code will fail if the depth changes or does not match the number of values that become keys...