I have an array like the following:
Array ( [1g27] => Array ( [42] => AAAAA [52] => BBBBB [4] => 2g4 ) [2g4] => Array ( [9] => CCCCC [14] => 3g14 [15] => 3g15 [20] => DDDDD [34] => EEEEE ) [3g14] => Array ( [49] => FFFFF ) [3g15] => Array ( [50] => GGGGG ) )
I would like it to become an array like the following:
Array ( [1g27] => Array ( [42] => AAAAA [52] => BBBBB [2g4] => Array ( [9] => CCCCC [3g14] => Array ( [49] => FFFFF ) [3g15] => Array ( [50] => GGGGG ) [20] => DDDDD [34] => EEEEE ) )
Notice that the values of the original array are also keys found in the original array. When there is a match between a value and an array, I want the array to replace the value (and rename that value's key).
I have tried foreach and array_walk_recursive, but I can't figure it out. (See following attempt which only goes 1 level deep.)
function inflate($flatree, $array) { global $inflatedtree; foreach ($array as $arraykey => $arrayvalue) { $inflatedtree[$arraykey] = $arrayvalue; if (array_key_exists($arrayvalue, $flatree)) { $inflatedtree[$arrayvalue] = $flatree[$arrayvalue]; inflate($flatree, $inflatedtree[$arrayvalue]); } } } inflate($flatree, $flatree['1g27']);
using this function, however, gives me this:
Array ( [42] => AAAAA [52] => BBBBB [2g4] => Array ( [9] => CCCCC [14] => 3g14 [15] => 3g15 [20] => DDDDD [34] => EEEEE ) [3g14] => Array ( [49] => FFFFF ) [3g15] => Array ( [50] => GGGGG ) )
I replaced the global variable $inflatedtree by a local one, which is the return value of the function inflate(). This return value is the new build branch.
function inflate($flatree, $array)
{
$inflatedtree = array();
foreach ($array as $arraykey => $arrayvalue) {
if (array_key_exists($arrayvalue, $flatree)) {
$inflatedtree[$arrayvalue] = inflate($flatree, $flatree[$arrayvalue]);
} else {
$inflatedtree[$arraykey] = $arrayvalue;
}
}
return $inflatedtree;
}
I use a function start() for the initial call to get back the array as wished. Calling inflate() directly will return the inner array.
function start($flatree, $key)
{
return array($key => inflate($flatree, $flatree[$key]));
}
$result_tree = start($flatree, '1g27');
I don't see a reason why your code should only go one level deep. It seems that you are calling the recursive function properly. The only error is that the key is not renamed but copied to a new name. You need to delete the old value like this
function inflate($flatree, $array)
{
global $inflatedtree;
foreach ($array as $arraykey => $arrayvalue)
{
$inflatedtree[$arraykey] = $arrayvalue;
if (array_key_exists($arrayvalue, $flatree))
{
unset($inflatedtree[$arraykey]);
//now the new stuff is only at $arrayvalue, not $arraykey
$inflatedtree[$arrayvalue] = $flatree[$arrayvalue];
inflate($flatree, $inflatedtree[$arrayvalue]);
}
}
}
inflate($flatree, $flatree['1g27']);
If your code ran on the example data does not give example results, then please post what array it makes otherwise.