使用匹配PHP删除多维数组中的元素

时间:2014-09-05 10:29:56

标签: php arrays multidimensional-array parent unset

我有这个多维数组:

[0] => Array
    (
        [id] => 55829
        [date] => 2014-09-05 07:00:56
        [customer] => Engineering
        [server] => example
        [status] => Successful
        [version] => 1
    )

[1] => Array
    (
        [id] => 55776
        [date] => 2014-09-05 06:58:30
        [customer] => Coating
        [server] => example
        [status] => Successful
        [version] => 1
    )

我希望能够遍历数组,如果是第二级客户' value匹配此数组中的值:

Array
(
    [0] => Engineering
    [1] => Painting
)

如果匹配,我想完全删除/取消设置父数组,这样第一个数组就是:

[0] => Array
    (
        [id] => 55776
        [date] => 2014-09-05 06:58:30
        [customer] => Coating
        [server] => example
        [status] => Successful
        [version] => 1
    )

5 个答案:

答案 0 :(得分:2)

以下应该适用于$records是多维数组且$second_array包含工程/绘画的地方。

<?php
foreach( $records as $key => $record )
{
    if( in_array( $record['customer'], $second_array ) )
    {
        unset( $records[ $key ] );  
    }
}
?>

答案 1 :(得分:0)

使用in_array

$array_to_filter = array(array(...));
$array_filter    = array(...);
foreach ($array_to_filter as $key => $value) {
    if (in_array($value['customer'], $array_filter)) {
        unset($array_to_filter['$key']);
    }
}

答案 2 :(得分:0)

尝试:

$types = array('Engineering', 'Painting');

foreach( $array as $key => $v ) {
    if( in_array($v['customer'], $types ) ) {
        unset($array[$key]);
    }
}

答案 3 :(得分:0)

你可以尝试:

$arrayBlackList = array('Engineering','Painting');

function shouldKeep($var)
{
    global $arrayBlackList;
    return !in_array($var['customer'],$arrayBlackList);
}

$filtered_array = array_filter($array1, "shouldKeep");

答案 4 :(得分:0)

$i = 0;
for ($i = 0; $i <count($array1) ; $i++) {

   if ($array1[$i]['customer'] == $array2[0] || $array1[$i]['customer'] == $array2[1]) {

       unset($array[$i]);

       // restart
       $i = 0
   }
}