Awa Melvine Awa Melvine - 11 days ago 4
PHP Question

how to remove object from array of objects in foreach loop php

I have a

users
object returned from the database that looks like this:

[
{
"id":1,
"name":"Bob",
"category":"admin",
"email":"test1@test.com",
"phone":"123456789",
"gender":"male",
},
{
"id":2,
"name":"John",
"category":"user",
"email":"john@test.com",
"phone":"123456789",
"gender":"male",
},
{
"id":3,
"name":"Jane",
"category":"admin",
"email":"jane@test.com",
"phone":"123456789",
"gender":"female",
},
]


Now I want to loop through all the
users
object and remove all users whose
category
attribute is
user
so that the resulting
users
object only remains with
admin
category.

I want to do this with a foreach loop. please how do I go about this or what better ways can I accomplish this?

Answer

I'm guessing the array was in JSON format? Anyways.. I fixed your invalid JSON so you should be able to see how it's done.

$json = '

[{
    "id": 1,
    "name": "Bob",
    "category": "admin",
    "email": "test1@test.com",
    "phone": "123456789",
    "gender": "male"
}, {
    "id": 2,
    "name": "John",
    "category": "user",
    "email": "john@test.com",
    "phone": "123456789",
    "gender": "male"
}, {
    "id": 3,
    "name": "Jane",
    "category": "admin",
    "email": "jane@test.com",
    "phone": "123456789",
    "gender": "female"
}]

';

$array = json_decode($json, true); //Fixed and converted JSON into PHP Assoc Array 

foreach($array as $k=>$v) { 
    foreach ($array[$k] as $key=>$value) { 
      if ($value === "user") { //If Value of 2D is equal to user

          unset($array[$k]); //Delete from Array 
      }
    }  
}

var_dump($array); //Output Array

Output

array(2) {
    [0] => array(6) {
        ["id"] => int(1)["name"] => string(3)
        "Bob" ["category"] => string(5)
        "admin" ["email"] => string(14)
        "test1@test.com" ["phone"] => string(9)
        "123456789" ["gender"] => string(4)
        "male"
    }[2] => array(6) {
        ["id"] => int(3)["name"] => string(4)
        "Jane" ["category"] => string(5)
        "admin" ["email"] => string(13)
        "jane@test.com" ["phone"] => string(9)
        "123456789" ["gender"] => string(6)
        "female"
    }
}