php unset multidimensional数组元素,其键值匹配

时间:2015-04-08 08:25:24

标签: php arrays multidimensional-array

我有一个多维数组:

Array
(
    [0] => stdClass Object
        (
            [user_type] => U
            [user_id] => 156
            [property_id] => 1201
        )

    [1] => stdClass Object
        (
            [user_type] => U
            [user_id] => 156
            [property_id] => 1200
        )

    [2] => stdClass Object
        (
            [user_type] => U
            [user_id] => 156
            [property_id] => 1196
        )

    [3] => stdClass Object
        (
            [user_type] => U
            [user_id] => 156
            [property_id] => 1193
        )
)

我想删除哪些值与property_id匹配的数组:

Array
(
    [0] => 1201
    [1] => 1200
    [2] => 1193
)

我想要这个结果:

Array
(
    [0] => stdClass Object
        (
            [user_type] => U
            [user_id] => 156
            [property_id] => 1196
        )
)

我正在为我所做的事分享我的代码:

for($b=0; $b<count($beBounceResults); $b++){
    $beBounceProID[] = $beBounceResults[$b]->property_id;
}
// Getting thus array in this variable $beBounceProID
Array
(
    [0] => 1201
    [1] => 1200
    [2] => 1193
)

$counter = "0";
foreach ($results as $key => $value){
    if($results[$key]->property_id == $beBounceProID[$counter]){
        unset($results[$key]);
    }
    $counter++;
}

但在此之后我得到了Notice: Undefined offset:

知道我做错了什么。

感谢。

2 个答案:

答案 0 :(得分:4)

试试这个

foreach ($results as $key => $value){
    if(in_array($results[$key]->property_id , $beBounceProID) )
    {
        unset($results[$key]);
    }
}

答案 1 :(得分:1)

另一种方法是过滤掉你不想要的数组:

$arr = array_filter($arr, function($v)use($property_id){
    return !in_array($v->property_id, $property_id);
});