php - Optimize multidimensional array creation
Get the solution ↓↓↓Solution:
You could go backwards through your input array and wrap the previous result as you go:
$nested = 'value';
for (end($keys); key($keys)!==null; prev($keys)){
$nested = [current($keys) => $nested];
}
At the end$nested
will have the desired structure.
Answer
Solution:
Give this a try. Here we're using references to stack our new arrays.
<?php
$keys = array('first', 'second', 'third');
$array = array();
$current = &$array;
foreach($keys as $key => $value) {
$current[$value] = array();
$current = &$current[$value];
}
$current = 'Hello world!';
print_r($array);
Answer
Solution:
Starting from the last Item you can loop through the array, pop the last one and build the new array:
<?php
$keys[0] = 'first';
$keys[1] = 'second';
$keys[2] = 'third';
function createKey($array) {
$b = "value";
while(count($array)>0) {
$key = array_pop($array);
$b = [$key => $b];
}
return $b;
}
var_dump(createKey($keys));
// Output:
array(1) {
["first"]=>
array(1) {
["second"]=>
array(1) {
["third"]=>
string(5) "value"
}
}
}
Answer
Solution:
Another option is to loop the reversed keys and wrap the previous result:
$array = [];
foreach(array_reverse($keys) as $key) {
$temp = $array;
unset($array[key($array)]);
$array[$key] = $temp;
}
Then you could set your value:
$array['first']['second']['third'] = 'value';
Answer
Solution:
You could eveneval
this in a safe way without leaking any input data into the eval-string:
$value = 'value';
eval( '$array[$keys['. implode(']][$keys[', range(0, count($keys)-1)) . ']] = $value;' );
or with an additional counter even simpler and shorter:
$value = 'value';
$i = 0;
eval( '$array' . str_repeat('[$keys[$i++]]', count($keys)) . ' = $value;' );
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: mysqli::real_connect(): (hy000/2002): connection refused
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.