array_filter php返回键不顺序

时间:2018-09-20 13:23:07

标签: php arrays object

我正在使用array_filter搜索并删除不需要的结果,我英语不好,这是我的做法:

$obj_Data = [
    [
        "id" => 1,
        "level" => "admin",
        "name" => "jack"
    ],
    [
        "id" => 2,
        "level" => "member",
        "name" => "john"
    ],
    [
        "id" => 3,
        "level" => "member",
        "name" => "jenny"
    ],
    [
        "id" => 4,
        "level" => "member",
        "name" => "whatever"
    ]
];
function filter_callback($element) {
    if ($element["level"] == "member") {
        return TRUE;
    }
    return FALSE;
}

$arr["data"] = array_filter($obj_Data, "filter_callback");
echo json_encode($arr);

它给我的结果是:

{
    "data": {
        "1": {
            "id": 2,
            "level": "member",
            "name": "john"
        },
        "3": {
            "id": 4,
            "level": "member",
            "name": "whatever"
        }
    }
}

这是我想要的结果:

{
    "data": {
        {
            "id": 2,
            "level": "member",
            "name": "john"
        },
        {
            "id": 4,
            "level": "member",
            "name": "whatever"
        }
    }
}

如何删除“ 1”和“ 3”?因为感谢您的阅读,我无法使用循环。

1 个答案:

答案 0 :(得分:2)

array_filter()保留使用的数组键,使结果数组成为JSON上下文中的对象。只需在通过JSON编码之前通过array_values()重新索引数组即可。