sha256
sha256

Reputation: 3099

Convert an array of 2-element arrays to an array making 2 elements as key => value

Is it possible to convert the following array using some PHP built-in functions to a array that contain the value of id as key and the value of label as the associated value? If not what's the efficient way?

Thanks.

Input Array:

Array
(
    [0] => Array
        (
            [id] => 2
            [label] => MTD-589
        )

    [1] => Array
        (
            [id] => 3
            [label] => MTD-789
        )

)

Output Array:

Array
(
  [2] => MTD-589,
  [3] => MTD-789,
)

Upvotes: 0

Views: 127

Answers (3)

Saturnix
Saturnix

Reputation: 10564

I don't know any built in function, but I'll do it this way:

assuming $originalArray as the array you want to convert

$newArray = array();

foreach ($originalArray as $element)
     $newArray[$element["id"]] = $element["label"];

output the result

var_dump($newArray);

Upvotes: 2

Rikesh
Rikesh

Reputation: 26421

Introducing array_column (still in PHP 5.5 Beta).

$new_array = array_column($your_array 'label', 'id');

OUTPUT:

Array
(
  [2] => MTD-589,
  [3] => MTD-789,
)

Using array_walk.

array_walk($array, function($a) use (&$return) { $return[$a['id']] = $a['label']; });
print_r($return);

Upvotes: 1

Jeff Hawthorne
Jeff Hawthorne

Reputation: 568

if you can make it so that one array has your IDs and one array has your labels, you can use array_combine to merge the two as key/value http://php.net/manual/en/function.array-combine.php

Upvotes: 0

Related Questions