删除关联数组的一部分

时间:2013-11-03 20:37:02

标签: php arrays associative-array

我想搜索一个关联数组,当我找到一个值时,删除那个数组部分。

以下是我的数组示例:

    Array
(
    [0] => Array
        (
            [id] => 2918
            [schoolname] => Albany Medical College
            [AppService] => 16295C0C51D8318C2
        )

    [1] => Array
        (
            [id] => 2919
            [schoolname] => Albert Einstein College of Medicine
            [AppService] => 16295C0C51D8318C2
        )

    [2] => Array
        (
            [id] => 2920
            [schoolname] => Baylor College of Medicine
            [AppService] => 16295C0C51D8318C2
        )
}

我想要做的是在16295C0C51D8318C2中找到值AppService,然后删除该部分数组。因此,例如,如果该代码是在上面的数组上运行的,那么整个数组都是空的,因为逻辑匹配该数组中的所有内容。

到目前为止,这是我的代码:

            foreach($this->schs_raw as $object) {
                if($object['AppService'] == "16295C0C51D8318C2") {
                    unset($object);
                }
        }

4 个答案:

答案 0 :(得分:4)

array_filter会有所帮助(http://php.net/manual/en/function.array-filter.php

$yourFilteredArray = array_filter(
    $this->schs_raw,
    function($var) {
        return $object['AppService'] != "16295C0C51D8318C2"
    }
);

答案 1 :(得分:2)

试试这样:

foreach ($this->schs_raw as &$object) {
    if($object['AppService'] == "16295C0C51D8318C2") {
        unset($object);
    }
}

最后:

foreach ($this->schs_raw as $k => $object) {
    if($object['AppService'] == "16295C0C51D8318C2") {
        unset($this->schs_raw[$k]);
    }
}

答案 2 :(得分:2)

试试这个:

foreach($this->schs_raw as $key=>$object) {
  if($object['AppService'] == "16295C0C51D8318C2") {      
    unset($this->schs_raw[$key]); // unset the array using appropriate index    
    break; // to exit loop after removing first item
  }
}

答案 3 :(得分:0)

为什么不创建新阵列?如果未找到匹配项,请将索引添加到新阵列...如果找到,请不要添加它。您的新阵列将只包含您想要的数据。