Question

I need to map

Array
(
    [0] => Array
        (
                [cid] => 1
                [value] => red
        )

    [1] => Array
        (
                [cid] => 2
                [value] => green
        )

    [2] => Array
        (
                [cid] => 3
                [value] => pink
        )

    [3] => Array
        (
                [cid] => 4
                [value] => yellow
        )
)

To:

Array
(
    [0] => 2
    [1] => 3
    [2] => 1
)

I need to map the second arrays value [0] => 2 to the cid in the first array. In other words I need 2 to map to value green.

Any help? THANK YOU.

Was it helpful?

Solution

I would first change the first array to something that is easier to check.

<?php
$temp = array();
foreach ($array1 as $val) {
  $temp[$val['cid']] = $val['value'];
}
?>

Now you have an array:

$temp[1] = "red";
$temp[2] = "green";
$temp[3] = "pink";
$temp[4] = "yellow";

Then you can easily use that in the second array

<?php
$new= array();
foreach ($array2 as $key=>$val) {
  $new[$key] = $temp[$val];
}
?>

Codepad example

OTHER TIPS

PHP >= 5.5.0

$colors = array_column($first, 'value', 'cid');

foreach($second as $value) {
    if(isset($colors[$value])) {
        echo $colors[$value];
    }
}

Where $first is your first array and $second obviously the second.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top