How can I flatten a two dimensional array into one dimensional array?
For example:
Array
(
[1] => Array
(
[key] => val
[key2] => val2
)
)
Becomes:
Array
(
[key] => val
[key2] => val2
)
for your example:
$myarray = array_shift($myarray);
or
$myarray = $myarray[1];
but:
could there be more than one sub-array?
if so: do this sub-arrays have keys with the same name?
if so: what should happen with the duplicates? rename them all? drop all but one?
as you can see, you'll have to give some more information on this. the question really isn't clear.
$array = array_shift($array);
this will take care of key also, its not necessary all array start with 0 or 1 or anything.
$array[1] would probably be simpler in that case.// for your example only and was mentioned to be suitable, therefore $array[1] is just as suitable. Your argument is like saying that not all arrays are stored in variables named $array, which is correct but should hopefully be obvious enough. The entire example only works if the outer array consists of 1 element only and is thus highly specific.$array = reset($array);. In any case this answer is very limited to the array in question only and does not reflect the general character of a Q&A. The warning note has been even removed.One obvious way would be to foreach over the array (preferrably by reference, to save copying all data over and over), and array_combine them into a new array.
Something like this:
$b = array();
foreach($arr as &$a) $b = array_combine($b, $a);
$arr = $b;
Though as others point out, in your particular special case array_shift is sufficient.
foreach docs says the opposite: "Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself". Do you have a reference for that (no pun intended), especially which versions do auto-referencing?function test($array){$array[0] = 2;} $test = array(1,2,3); test($test); print_r($test); and you should get array(2,2,3) even though it wasn't passed by reference. Even happens if you do $var = $test; $test[0] = 2; print_r($var); and you'll get array(2,2,3) from $var even though you only changed the value of $test[0]. I think they changed it in 5.2 or somewhere around there.