如何从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,那么这将被删除.我已经将代码更改为现在测试密钥(类别)以及值. *

相关文章

Hessian开源的远程通讯,采用二进制 RPC的协议,基于 HTTP 传输。可以实现PHP调用Java,Python,C#等多语...
初识Mongodb的一些总结,在Mac Os X下真实搭建mongodb环境,以及分享个Mongodb管理工具,学习期间一些总结...
边看边操作,这样才能记得牢,实践是检验真理的唯一标准.光看不练假把式,光练不看傻把式,边看边练真把式....
在php中,结果输出一共有两种方式:echo和print,下面将对两种方式做一个比较。 echo与print的区别: (...
在安装好wampServer后,一直没有使用phpMyAdmin,今天用了一下,phpMyAdmin显示错误:The mbstring exte...
变量是用于存储数据的容器,与代数相似,可以给变量赋予某个确定的值(例如:$x=3)或者是赋予其它的变...