As the title with the example says, I need a flat array to be nested by each following key being the previous value.
Example:
array("I", "need", "this", "to", "be", "nested"); // To: array("I" => array("need" => array("this" => array("to" => array("be" => array("nested"))))))
Flattening a two-dimensional arrayarray_merge(... $twoDimensionalArray); array_merge takes a variable list of arrays as arguments and merges them all into one array. By using the splat operator ( ... ), every element of the two-dimensional array gets passed as an argument to array_merge .
=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass .
Here is a possible implementation:
<?php function make_nested($array) { if (count($array) < 2) return $array; $key = array_shift($array); return array($key => make_nested($array)); } print_r(make_nested(array("I", "need", "this", "to", "be", "nested")));
If you don't like recursion, here is an iterative version:
function make_nested($array) { if (!$array) return array(); $result = array(array_pop($array)); while ($array) $result = array(array_pop($array) => $result); return $result; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With