如何从foreach循环php中的对象数组中删除对象

前端之家收集整理的这篇文章主要介绍了如何从foreach循环php中的对象数组中删除对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个从数据库返回的用户对象,如下所示:
[
    {
        "id":1,"name":"Bob","category":"admin","email":"test1@test.com","phone":"123456789","gender":"male",},{
        "id":2,"name":"John","category":"user","email":"john@test.com",{
        "id":3,"name":"Jane","email":"jane@test.com","gender":"female",]

现在,我想循环遍历所有用户对象,并删除其category属性为user的所有用户,以便生成用户对象仅保留为admin类别.

我想用foreach循环来做这个.请问我该如何解决这个问题,或者我有什么更好的方法来实现这个目标?

我猜这个数组是JSON格式的吗?无论如何..我修复了你的无效JSON,所以你应该能够看到它是如何完成的.
$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",{
    "id": 3,"name": "Jane","email": "jane@test.com","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

产量

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"
    }
}

编辑

*正如@sevavietl在评论中指出的那样,如果数组的任何其他元素被称为user,那么这将被删除.我已经将代码更改为现在测试密钥(类别)以及值. *

猜你在找的PHP相关文章