Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Turning multidimensional arrays to single dimension arrays

Tags:

arrays

php

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

like image 975
KeyStroke Avatar asked Mar 09 '10 12:03

KeyStroke


People also ask

How can I create a multidimensional array to a single array in PHP?

This single line would do that: $array = array_column($array, 'plan'); The first argument is an array | The second argument is an array key.

How do I convert multiple arrays into one array?

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.

How do you clear a multidimensional array in PHP?

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 ?>

How we can convert a multidimensional array to string without any loop?

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.


1 Answers

$result = call_user_func_array('array_merge', $array);
like image 51
user187291 Avatar answered Sep 28 '22 08:09

user187291