6

I have a users object returned from the database that looks like this:

[
    {
        "id":1,
        "name":"Bob",
        "category":"admin",
        "email":"[email protected]",
        "phone":"123456789",
        "gender":"male",
    },
    {
        "id":2,
        "name":"John",
        "category":"user",
        "email":"[email protected]",
        "phone":"123456789",
        "gender":"male",
    },
    {
        "id":3,
        "name":"Jane",
        "category":"admin",
        "email":"[email protected]",
        "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?

3
  • 3
    Why don't you just select the 'admin' rows from the table in the first place? Commented Nov 29, 2016 at 12:25
  • 1
    No idea what happend here but someone is downvoting answers below. Check our solutions and give feedback ;) Commented Nov 29, 2016 at 13:09
  • @KarolGasienica Make a check on peoples rep, it becomes clear then. Commented Nov 29, 2016 at 13:11

4 Answers 4

6

Assuming the array is in json format, one line code:

$users = array_filter(json_decode($users), function($user) {
    return $user->category != 'user';
});

If it is instead already a valid php array simply remove the json_decode()

Sign up to request clarification or add additional context in comments.

3 Comments

why do you need ARRAY_FILTER_USE_BOTH here, if you are using only the value in the callback function?
regardless to this, this is the best-suited answer, don't know why it is downvoted. other answers just reinvent array_filter function.
Well, technically question asked for a foreach loop solution. Moreover, this method does not work in-place, which can be bad if the array is big. I doubt any of those are actual causes though, someone is carpet-downvoting answers here. Maybe that someone will post (or already has posted) his answer.
3

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": "[email protected]",
    "phone": "123456789",
    "gender": "male"
}, {
    "id": 2,
    "name": "John",
    "category": "user",
    "email": "[email protected]",
    "phone": "123456789",
    "gender": "male"
}, {
    "id": 3,
    "name": "Jane",
    "category": "admin",
    "email": "[email protected]",
    "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 ($key === "category" && $value === "user") { //If Value of 2D is equal to user and cat

          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)
        "[email protected]" ["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)
        "[email protected]" ["phone"] => string(9)
        "123456789" ["gender"] => string(6)
        "female"
    }
}

Edit

*As @sevavietl pointed out in the comments, if any other element of the array was called user, then this would be removed. I've changed code to now test the key (category) as well as the value. *

6 Comments

You can also add $array = array_values($array) at the end if you want to reset keys
@maestroosram That's IF the keys need resetting...he may need them for reference elsewhere in his code.
what if the name of an admin will be "user"? the element will be removed from resulting array, although the category is "admin". going even further, you don't break from the inner loop after unsetting element.
@Kitson88, it will work. but why do you need this nested loop, when you just can get the category like this $v['category']? If it is done from concern, that there will be no key category, you can check this with isset($v['category']).
@Kitson88, as I wrote in the other comment maestroosram solution is the best. But for whatever reason, someone downvoted all answers and his answer got -1. Which is a shame. Nowadays, when you can avoid explicit loops it is usually better to do so.
|
1

If you just want to remove the category "user", you just have to get the key and make a condition for removing that category and put the category "admin" on that new array. Have a look at this:

$json = '
[{
    "id": 1,
    "name": "Bob",
    "category": "admin",
    "email": "[email protected]",
    "phone": "123456789",
    "gender": "male"
}, {
    "id": 2,
    "name": "John",
    "category": "user",
    "email": "[email protected]",
    "phone": "123456789",
    "gender": "male"
}, {
    "id": 3,
    "name": "Jane",
    "category": "admin",
    "email": "[email protected]",
    "phone": "123456789",
    "gender": "female"
}]';

$arr = json_decode($json, true);

$newArr = array();
foreach($arr as $key => $value) {
    if($value["category"] == "admin") {
        $newArr[] = $value;
    }
}

echo '<pre>';
    print_r($newArr);
echo '</pre>';

1 Comment

I was shocked to notice that too, being the author of the question. But you all really helped me.
1

Your input looks like JSON, so you can use json_decode function to make it an array, which you can foreach, and you can encode (json_encode) it back to JSON if you want same output.


Solution

Code below should be useful for you:

<?php
// $json = output from your db
$json_output = json_decode($json, true);

foreach ($json_output as $user) {
    if ($user['category'] == 'admin') { // or it may be $user['category'] != 'user'
        $user_output[] = $user;
    }
}
print_r($user_output);
print_r(json_encode($user_output, true)); // if you want json output    
?>

SQL

You can also add in your SQL query WHERE statement. It might look as follows:

SELECT * FROM users WHERE category = 'admin'

Of course query depends on names which you have in your table. More about SELECT query you can read in manuals below.


Manuals

More about used methods you can read below:


Compiler online

You can check how it works here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.