avatar
remove elements from array based on another array PHP

• The issue at hand is the removal of elements from one array based on another array.

» Input:

$obj1 = [["instruction_id" => 133]];
$obj2 = [["instruction_id" => 131], ["instruction_id" => 132], ["instruction_id" => 133]];

» Using array_map and array_filter:

$obj1 = [["instruction_id" => 133]];
$obj2 = [["instruction_id" => 131], ["instruction_id" => 132], ["instruction_id" => 133]];
$instruction_ids_to_remove = array_map(function($item) {
    return $item["instruction_id"];
}, $obj1);
$obj2 = array_filter($obj2, function($item) use ($instruction_ids_to_remove) {
    return !in_array($item["instruction_id"], $instruction_ids_to_remove);
});
$obj2 = array_values($obj2);

Note:

[["instruction_id" => 133]] -> JSON String -> json_decode() to convert to array.
array (
  0 => 
  array (
    'instruction_id' => 131,
  ),
  1 => 
  array (
    'instruction_id' => 132,
  ),
) -> PHP Array -> json_encode() to convert to string.
24
remove invalid elements from array in PHP remove an object from array remove last character from String remove underline for anchors tag remove object from array by property value
You need to login to do this manipulation!