Mentos93 Mentos93 - 4 months ago 9
PHP Question

Change the content of an array to be more efficient

When doing a

print_r
on my array, I get the following output;

Array
(
[0] => Array
(
[id] => 178
[name] => Briar Price
)

[1] => Array
(
[id] => 90
[name] => Bradley Kramer
)

[2] => Array
(
[id] => 508
[name] => Calvin Yang
)

[3] => Array
(
[id] => 457
[name] => Charles Valenzuela
)

... and so on


How can I modify the array to look like this;

Array
(
[178] => Briar Price
[90] => Bradley Kramer
[508] => Calvin Yang
[457] => Charles Valenzuela
... and so on
)


I just want to make the ID the key for the value name. I always have issues when it comes to arrays reordering.

Answer

Use foreach() -

$newArr = array();
foreach ($your_array as $key => $val) {
  $newArr[$val['id']] = $val['name'];
}

print_r($newArr) // desired output