John Smith
John Smith

Reputation: 87

How to convert array of arrays to associated array in PHP

I have a table in my database for storing settings. It contains columns of 'id', 'name' and 'value'. I need to select all of them and use the keys to get the values simply.

SELECT * FROM settings

The result is:

array( array(id1, name1, value1), array(id2, name2, value2), ... )

I need call the values simply, like:

$value1 = $settings['name1'];

So I should convert the result array to this:

array( name1 => value1, name2 => value2, ... )

How can I do this using PHP ?

Upvotes: 1

Views: 83

Answers (2)

michael.schuett
michael.schuett

Reputation: 4771

Just through i would offer this as well. This will allow you to get what you want without ever creating the copy. You also get the efficiency of a reverse loop if this happens to be a very long array.

$array = array( array("key1" => "value1"), array("key2" => "value2") );

for($i = sizeof($array) - 1; $i > -1; $i--) {
    $key = array_keys($array[$i])[0];
    $value = $array[$i][$key];
    unset($array[$i]);
    $array[$key] = $value;
}

var_dump($array);

Or if we want everyone to be like whats going on when they read it we can do this. although you now are making two calls to array_keys which is less than optimal.

$array = array( array("key1" => "value1"), array("key2" => "value2") );

for($i = sizeof($array) - 1; $i > -1; $i--) {
    $array[array_keys($array[$i])[0]] = $array[$i][array_keys($array[$i])[0]];
    unset($array[$i]);
}

var_dump($array);

You would have to modify the indices and a few other things since the OP has changed the question from the original one as usual but with the original array posted this would work and i'm sure you could figure out how to modify it to work with the new array.

Upvotes: 0

georg
georg

Reputation: 214959

You can achieve that with a cascade of built-in functions, for example:

$a = array( array("key1" => "value1"), array("key2" => "value2"), array("key3" => "value3"));

$b = array_combine(
    array_map('key', $a),
    array_map('end', $a));

or

$b = array_reduce($a, function($x, $y) { return $x + $y; }, $a[0]);

However, loops in php are usually cleaner, easier to understand and more efficient:

$b = array();
foreach($a as $item)
    $b += $item;

There's no sound reason to avoid loops.

UPD, as per your update

$a = array( array('id1', 'name1', 'value1'), array('id2', 'name2', 'value2'));

$b = array_combine(
    array_column($a, 1),
    array_column($a, 2));

returns [name1] => value1, [name2] => value2

If your php doesn't support array_column, you can include the shim, or just use a loop, which, once again, turns out to be simpler and more readable:

foreach($a as $x)
    $result[ $x[1] ] = $x[2]; 

Upvotes: 2

Related Questions