vinz
vinz

Reputation: 348

Unset a multidimensional array with another multidimensional array with values than key

Array#1     
Array(
        [0] => Array(
            [id] => 0
            [name] => a
        )
        [1] => Array(
            [id] => 1
            [name] => b
        )
        [2] => Array(
            [id] => 2
            [name] => c
        )
    )

Array #2
Array(
    [0] => Array(
        [id] => 0
        [name] => c
    )
    [1] => Array(
        [id] => 1
        [name] => a
    )
)

I would like to unset the first array with the second array referencing by the name because the key changes all the time.

I'm stuck with looping with removing it with name than key with this. Any help is much appreciated!

I would like to remove whatever array#2 has in array#1.

Final Array 
Array(
         [0] => Array(
             [id] => 1
             [name] => b
         )
     }

Upvotes: 1

Views: 64

Answers (1)

Expedito
Expedito

Reputation: 7795

$arr = Array(
    0 => array(
        'id' => 0,
        'name' => 'a'),
    1 => array(
        'id' => 1,
        'name' => 'b'),
    2 => array(
        'id' => 2,
        'name' => 'c'));
$arr2 = Array(
    0 => array(
        'id' => 0,
        'name' => 'c'),
    1 => array(
        'id' => 1,
        'name' => 'a'));


$ex = array_map(function($a) {return $a['name'];}, $arr2);
foreach ($arr as $key => $value){
    if (in_array($value['name'], $ex)){
        unset($arr[$key]);
    }
}
print_r($arr);

Output:

Array
(
    [1] => Array
        (
            [id] => 1
            [name] => b
        )

)

Upvotes: 2

Related Questions