Basically my app is interacting with a web service that sends back a weird multidimensional array such as:
Array
(
[0] => Array
(
[Price] => 1
)
[1] => Array
(
[Size] => 7
)
[2] => Array
(
[Type] => 2
)
)
That's not a problem, but the problem is that the service keeps changing the index of those items, so in the next array the Price could be at 1 instead of 0.
How do I effeciently transform arrays like this into a single dimension array so I can access the variables through $var['Size'] instead of $var[1]['Size']?
Appreciate your help
This single line would do that: $array = array_column($array, 'plan'); The first argument is an array | The second argument is an array key.
Using concat method The concat method will merge two or more arrays into a single array and return a new array. In the code above, we have merged three arrays into an empty array. This will result in merging multiple arrays into a new array.
Using "array(array())" will create a 2D array with an "empty" element in the first position. To create a truly blank 2D array this needs to be removed. <? php $emptyArray = array(array()); // Creates a 2D array with one empty element in $emptyArray[0] array_pop($emptyArray); // Pops element[0] off the array ?>
Maybe in case you need to convert a multidimensional array into a string, you may want to use the print_r() function. This is also called “array with keys”. By adding “true” as its second parameter, all the contents of the array will be cast into the string.
$result = call_user_func_array('array_merge', $array);
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