Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove part of associative array [duplicate]

I want to search an associative array and when I find a value, delete that part of the array.

Here is a sample of my 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
        )
}

What I want to do is find the value 16295C0C51D8318C2 in the AppService and then delete that part of the array. So, for example, if that code was to run on the above array, it was empty out the entire array since the logic matches everything in that array.

Here is my code so far:

            foreach($this->schs_raw as $object) {
                if($object['AppService'] == "16295C0C51D8318C2") {
                    unset($object);
                }
        }
like image 241
Richard M Avatar asked Nov 02 '25 18:11

Richard M


2 Answers

array_filter will help (http://php.net/manual/en/function.array-filter.php)

$yourFilteredArray = array_filter(
    $this->schs_raw,
    function($var) {
        return $object['AppService'] != "16295C0C51D8318C2"
    }
);
like image 86
bukart Avatar answered Nov 05 '25 09:11

bukart


Try like this:

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

Eventually:

foreach ($this->schs_raw as $k => $object) {
    if($object['AppService'] == "16295C0C51D8318C2") {
        unset($this->schs_raw[$k]);
    }
}
like image 31
speccode Avatar answered Nov 05 '25 07:11

speccode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!