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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With