Generate multi-dimensional array from an array in php?

0

Issue

I’ve a list of associative arrays as below:

[
"country" => "AU",
"state" => "VIC",
"suburb" => "Carlton",
"precedence" => ["country", "state", "suburb"]
]

And I want a new multidimensional array like below where the elements are nested based on the order defined by precedence key on first array:

[
 "country" => [
  "AU" => [
    "state" => [
      "VIC" => [
        "suburb" => "Carlton
      ]
     ]
    ]
   ]
]

The above is just an example and I want a generic solution that will work for any kinds of array. Only 1 condition that’ll be satisfied by all input arrays is that they’ll have a precedence element denoting the order in which the output array needs to be generated.

I’ve tried some recursive solution but it’s not working as expected and I’ve got PHP Fatal error: Allowed memory size of 1073741824 bytes exhausted (looks like it’s running infinitely):

function generateArray(&$array)
    {
        foreach ($array['precedence'] as $key => $property) {
            if ($key == sizeof($array['precedence']) - 1) {
                return [$property => $array[$property]];
            } else {
                return generateAssetConfig($array);
            }
        }
    }

Solution

You could loop the reversed items of the precedence part.

If there are no items in the result array yet, add the first key => value pair.

Else wrap the current result in a multidimensional array, setting the current value if the iteration as the outer key, and wrap the value (for that key in the source array) together with the current result in a second array.

$source = [
    "country" => "AU",
    "state" => "VIC",
    "suburb" => "Carlton",
    "precedence" => ["country", "state", "suburb"]
];

function generateArray($array)
{
    $result = [];
    foreach(array_reverse($array["precedence"]) as $v) {
        $result =! $result ? [$v => $array[$v]] : [$v => [$array[$v] => $result]];
    }
    return $result;
}

var_export(generateArray($source));

Output

array (
  'country' => 
  array (
    'AU' => 
    array (
      'state' => 
      array (
        'VIC' => 
        array (
          'suburb' => 'Carlton',
        ),
      ),
    ),
  ),
)

Answered By – The fourth bird

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More