4

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);
                }
        }
Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
Richard M
  • 1,445
  • 2
  • 13
  • 20

4 Answers4

4

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"
    }
);
bukart
  • 4,906
  • 2
  • 21
  • 40
3

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]);
    }
}
speccode
  • 1,562
  • 9
  • 11
2

Try this:

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
  }
}
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Althaf M
  • 498
  • 4
  • 12
0

Why not create a new array? If match not found, add index to new array... If it is found, don't add it. Your new array will only contain the data you want.

Gavin
  • 2,123
  • 1
  • 15
  • 19
  • Imagine an array is used way too many times in the application, and a logic should be implemented, where this array is going to be modified – Royal Bg Nov 03 '13 at 20:42