jmccartie
jmccartie

Reputation: 4976

Reduce a 2d array to a flat associative array using one column as keys and another column as values

How do I get this array:

Array
(
    [0] => Array
        (
            [max] => 5
            [year] => 2007
        )

    [1] => Array
        (
            [max] => 6.05
            [year] => 2008
        )

    [2] => Array
        (
            [max] => 7
            [year] => 2009
        )

)

Into this format:

[year] => [max]

Upvotes: 0

Views: 129

Answers (3)

cletus
cletus

Reputation: 625017

Simple way?

$dest = array();
foreach ($src as $k => $v) {
  $dest[$v['year']] = $v['max'];
}

Upvotes: 1

Josh Curren
Josh Curren

Reputation: 10226

you would need to iterate through your current array and put the data into a new array.

$result = array();
foreach($currenArray as $x) 
{
    $result[$x['year']] = $x['max'];
}

Upvotes: 1

José Leal
José Leal

Reputation: 8109

$result = array();
foreach($array as $v) {
    $result[$v['year']] = $v['max'];
}

There you go.

Upvotes: 5

Related Questions