简体   繁体   中英

Remove from 2d array if it belongs in array

I'm trying to remove arrays in the cars array if the make value belongs in the retiredCars array. I did run into array_search but I'm not sure how to apply it to a multi dimensional array

$retiredCars = array("Saab", "Saturn", "Pontiac");

$cars = array
  (
  array('make' => 'BMW', 'model' => '325'),
  array('make' => 'Saab', 'model' => '93'),
  array('make' => 'Pontiac', 'model' => 'GTO')
  );

In the example above, the $cars array should only contain the 'BMW' array after processing

foreach ($cars as $key => $arr) {
    if (in_array($arr['make'], $retiredCars))
        unset($cars[$key]);
}

Unsetting array's elements while iterating over it doesn't seem a good approach. Another idea:

$array_elem_passes = function ($val) use ($retiredCars)
{
        if (in_array($val['make'], $retiredCars))
                return false;

        return true;
};

$ret = array_filter($cars, $array_elem_passes);  

You can use array_filter, for performance flip the retiredCars array. Live demo

You also can use array_udiff to make it. Refer to this post .

<?php
$retiredCars = array("Saab", "Saturn", "Pontiac");

$cars = array
  (
  array('make' => 'BMW', 'model' => '325'),
  array('make' => 'Saab', 'model' => '93'),
  array('make' => 'Pontiac', 'model' => 'GTO')
  );

$makes = array_flip(array_unique($retiredCars));
print_r(array_filter($cars, function($v)use($makes){return isset($makes[$v['make']]);}));

Yes. array_udiff do the trick in this way

$res = array_udiff($cars, $retiredCars, 
     function($c, $r) { 
         // You need test both variable because udiff function compare them in all combinations
         $a = is_array($c) ? $c['make'] : $c;
         $b = is_array($r) ? $r['make'] : $r;
         return strcmp($a, $b); 
         });

print_r($res);

demo on eval.in

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM