0

i wanted to fill an assoc array from variables from another array.

I have an array like this

$keys = array("key1", "key2", "key3");

and now i want to fill an array with these keys like this

$someArray["key1"]["key2"]["key3"] = "some value";

and of course it would work like this as well

$someArray[$keys[0]][$keys[1]][$keys[2]] = "some value";

But the number of keys may vary and they are different for each loop. I want to translate some data in a hierarchy structure.

So I would love to do this dynamically from the $keys array.

For now I create a Json String, push the decoded Json to $someArray and use array_merge on it - but i thought there should be a more elegant way.

Thank you guys

1 Answer 1

1

Use a loop with a reference variable:

$someArray = array();
$where =& $someArray;
foreach (array_slice($keys, 0, -1) AS $key) {
    $where[$key] = array();
    $where =& $where[$key];
}
$where[$keys[count($keys)-1]] = "some value";
Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much - i had no idea what you use reference variables for so far :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.