KeyStroke KeyStroke - 29 days ago 11
PHP Question

PHP: Turning multidimensional arrays to single dimension arrays

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

Answer

Like this:

$result = array();

foreach($array as $inner) {
    $result[key($inner)] = current($inner);        
}

The $result array would now look like this:

Array
(
    [Price] => 1
    [Size] => 7
    [Type] => 2
)