Change the contents of the array to be more efficient

When executed print_rin 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 change 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 identifier the key for the value name. I always have problems when it comes to reordering arrays.

+4
source share
4 answers

Use foreach () -

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

print_r($newArr) // desired output
+3
source

Pass the third parameter to make its key as array_column

$array = array_column($users, 'name', 'id');

print_r($array);
+6
source

array_column array_combine PHP .

,

<?php
    $keys=array_column($mainarray,'id');
    $values=array_column($mainarray,'name');

    $finalarray=array_combine($keys,$values);

$finalarray .

array_combine , , .

array_column returns values ​​from a single column in the input array.

+3
source

I would use array_combinethat attaches new keys to values

$results = [
    ['id'=>1,'name'=>'John'],['id'=>2,'name'=>'Jane'],
];

$results = array_combine(
    array_column($results,'id'), //use 'id' column as keys
    array_column($results,'name') //use 'name' column as values
);
//now $results is [1=>'John', 2=>'Jane']
+3
source

All Articles