phparraysmultidimensional-arrayfilterdifference

Remove rows from a 2d array if two column values are found in two columns of any row in another 2d array


I have two 2d arrays.

$array1 = [
    ['quantity' => 13, 'idname' => 3, 'x_name' => 'Name-3'],
    ['quantity' => 5, 'idname' => 4, 'x_name' => 'Name-4']
];

$array2 = [
    ['id_x' => 3, 'x_name' => 'Name-3', 'id_l' => 4],
    ['id_x' => 4, 'x_name' => 'Name-4', 'id_l' => 8],
    ['id_x' => 5, 'x_name' => 'Name-5', 'id_l' => 7],
    ['id_x' => 6, 'x_name' => 'Name-6', 'id_l' => 5]
];

I need to remove rows from the second array if a row from the first array contains two corresponding column values.

  1. Array1[][idname] = Array2[][id_x] and
  2. Array1[][x_name] = Array2[][x_name] (of course)

My desired output:

[
    ['id_x' => 5, 'x_name' => 'Name-5', 'id_l' => 7],
    ['id_x' => 6, 'x_name' => 'Name-6', 'id_l' => 5]
]

Solution

  • You can use nested foreach loops. If the value from the current element of array2 is found in array1, remove the element:

    foreach($array2 as $key => $value){
        foreach($array1 as $val){
            if($value['x_name']==$val['x_name']){
                unset($array2[$key]);
                $break;
            }
        }
    }
    var_dump($array2);
    

    Live example: http://codepad.viper-7.com/eOOUi6