如果在php中包含特定项,如何从多维数组中删除数组

时间:2018-02-06 10:54:54

标签: php arrays multidimensional-array

在:

$cars = array
  (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );

我想删除整个阵列女巫包括“宝马”作为项目

结果如下:

$cars = array
  (
  array("Volvo",22,18),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );

7 个答案:

答案 0 :(得分:5)

您可以使用array_filter根据自定义逻辑从数组中删除元素。如果应该分别保留或删除元素,则回调函数应返回truefalse

$filter = 'BMW';

$cars = array_filter($cars, function($car) use ($filter) {
    return $car[0] !== $filter;
});

在这里,我们会过滤掉第一个元素等于$filter变量的所有行。

请参阅https://eval.in/950579

答案 1 :(得分:3)

只是为了扩展@iainn的回答

'宝马'可能并不总是第一个因素,所以...... in_array()

$filter = 'BMW';

$filteredCars = array_filter($cars, function($car) use($filter){
                       return in_array($filter, $car) === false;
                });

答案 2 :(得分:1)

我做了这个小功能,请记住,汽车制造必须是关键[0]。

示例

<?php
$cars = array
(
    array("Volvo", 22, 18),
    array("BMW", 15, 13),
    array("Saab", 5, 2),
    array("Land Rover", 17, 15)
);

function removeCar (array $cars, string $name): array
{
    $returnArray = array();
    foreach ($cars as $array => $car) {
        if ($car[0] != $name) {
            $returnArray[] = $car;
        }
    }
    return $returnArray;
}

$cars = removeCar($cars, "BMW");
print_r($cars);

<强>输出

Array ( [0] => Array ( [0] => Volvo [1] => 22 [2] => 18 ) [1] => Array ( [0] => Saab [1] => 5 [2] => 2 ) [2] => Array ( [0] => Land Rover [1] => 17 [2] => 15 ) )

希望这会有所帮助。问候。

答案 3 :(得分:1)

你可以这样做:

bash ./vip_monitor.sh

答案 4 :(得分:1)

您可以使用array_intersect_keyarray_column

// Exclude one car.
$exclude = 'BMW';
$result = array_intersect_key($cars, array_filter(
    array_column($cars, 0),
    function ($car) use ($exclude) {
        return $car !== $exclude;
    }
));

var_dump($result);

// Exclude multiple cars.
$exclude = ['BMW', 'Saab'];
$result = array_intersect_key($cars, array_diff(array_column($cars, 0), $exclude));

var_dump($result);

这是the demo

答案 5 :(得分:0)

您可以使用foreach()循环检查每个数组。

   $cars = array
      (
      array("Volvo",22,18),
      array("BMW",15,13),
      array("Saab",5,2),
      array("Land Rover",17,15)
      );


    $cars_filtered = array();  
    foreach($cars as $single){
        if($single[0]!='BMW'){
            $cars_filtered[] = $single;
        }   
    }

    print_r($cars_filtered);

答案 6 :(得分:0)

排除数组中存在的项目。您可以array_flipisset

执行此操作
foreach($cars as $key=>$value)  {
  if(isset(array_flip($value)["BMW"])){
    unset($cars[$key]);
  }
}

现场演示:https://eval.in/950611

Array
(
    [0] => Array
        (
            [0] => Volvo
            [1] => 22
            [2] => 18
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
            [2] => 2
        )

    [3] => Array
        (
            [0] => Land Rover
            [1] => 17
            [2] => 15
        )

)