Alex Pliutau
Alex Pliutau

Reputation: 21957

Convert 2d array into a flat, associative array deriving keys and values from two columns

I have the next array

Array ( 
   [0] => Array ( [id] => 22 [title] => RankTitle ) 
   [1] => Array ( [id] => 32 [title] => RankTitle2 ) 
) 

How can I get the next array in php?:

Array ( 
   [22] => RankTitle 
   [32] => RankTitle2 
) 

Upvotes: 0

Views: 886

Answers (3)

MAZux
MAZux

Reputation: 971

You can do it like this:

$newArray = array_combine(
    array_column($oldArray, 'column_to_be_key'),
    array_column($oldArray, 'column_to_be_value'),
);

Update

It can be achieved by array_column, see 2nd example in php offical doc

$newArray = array_column($oldArray, 'column_to_be_value', 'column_to_be_key');

Upvotes: 0

axsuul
axsuul

Reputation: 7480

Do you mean this?

$array = Array ( 
            [0] => Array ( [id] => 22 [title] => RankTitle ) 
            [1] => Array ( [id] => 32 [title] => RankTitle2 ) 
         ) 

$nextArray = array($array[0]['id'] => $array[0]['title'],
                   $array[1]['id'] => $array[1]['title']);

Upvotes: 1

Gumbo
Gumbo

Reputation: 655249

You can do this:

$new = array();
foreach ($old as $item) {
    $new[$item['id']] = $item['title'];
}

Upvotes: 4

Related Questions