Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smarter way to use array entry value as key

Tags:

php

Do you know a smarter way to use an array entry value as key?

Consider this array:

$array = [
    0 => [
        'id' => 1,
        'title' => 'Title 1',
    ],
    2 => [
        'id' => 2,
        'title' => 'Title 1',
    ],
    3 => [
        'id' => 3,
        'title' => 'Title 1',
    ]
];

To replace each array key with value of id I do this:

$new_array = [];

foreach ($array AS $item) {
    $new_array[$item['id']] = $item;
}

unset($array);
like image 896
Cudos Avatar asked Mar 05 '23 10:03

Cudos


1 Answers

$array = array_column($array, null, 'id');

Look at the description of the column_key and index_key arguments: http://php.net/array_column.

like image 52
deceze Avatar answered Mar 16 '23 10:03

deceze