Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending 2 arrays depending on a value

Tags:

I have two example arrays:

$array1 = array(
    0 => array("a" => '123', "b" => 234),
    1 => array("a" => 'abs', "b" => 234),
    2 => array("a" => '123', "b" => 234),
    3 => array("a" => 'abs', "b" => 234),
    4 => array("a" => '123', "b" => 234),
    5 => array("a" => 'abs', "b" => 898),
    6 => array("a" => '123', "b" => 234),
    7 => array("a" => 'abs', "b" => 234),
    8 => array("a" => '123', "b" => 234),
    9 => array("a" => 'abs', "b" => 898)
);

$array2 = array(
    0 => array("b" => '234', "c" => "Herr"),
    1 => array("b" => '898', "c" => "Frau"),
);

Array 1 should be extended by c, depending on the value in b, which is present in both arrays. Finally, array 1 should look like this:

$array3 = array(
    0 => array("a" => '123', "b" => 234, "c" => "Herr"),
    1 => array("a" => 'abs', "b" => 234, "c" => "Herr"),
    2 => array("a" => '123', "b" => 234, "c" => "Herr"),
    3 => array("a" => 'abs', "b" => 234, "c" => "Herr"),
    4 => array("a" => '123', "b" => 234, "c" => "Herr"),
    5 => array("a" => 'abs', "b" => 898, "c" => "Frau"),
    6 => array("a" => '123', "b" => 234, "c" => "Herr"),
    7 => array("a" => 'abs', "b" => 234, "c" => "Herr"),
    8 => array("a" => '123', "b" => 234, "c" => "Herr"),
    9 => array("a" => 'abs', "b" => 898, "c" => "Frau")
);

Are there already simple ways to realize this in PHP7.x?

like image 729
rebelhig Avatar asked Aug 29 '19 05:08

rebelhig


1 Answers

Make an iteration over $array1 using array_walk(). In use() scope pass the filter array prepared (['234' => 'Herr', '898' => 'Frau']) from $array2. In every cycle of the iteration get value from $filter array by the index value of b and set it to $array1's c index. Example:

$filter = array_column($array2, 'c', 'b');
array_walk($array1, function(&$val) use ($filter) { 
    $val['c'] = $filter[$val['b']]; 
});
print_r($array1);

Working demo.

like image 107
MH2K9 Avatar answered Oct 12 '22 22:10

MH2K9