array_filter 将索引数组转换为关联数组

array_filter converting an indexed array to an associative array

我有一个包含一些关联数组的索引数组,我应用了一个简单的

$my_arr = array_filter($my_arr, function($obj) {
    return $obj["value"] < 100;
});

用于过滤数组中某些项目的函数。

这开始让我的 Angular 前端出现奇怪的错误,所以几分钟后我发现 $my_arr 正在从索引数组转换为关联数组。

编辑:根据评论中的要求,我的 $my_arr:

$my_arr = [
    ["foo" => "bar", "value" => 10],
    ["foo" => "var", "value" => 30],
    ["foo" => "car", "value" => 440],
    ["foo" => "dar", "value" => 700]
]

编辑:我的代码中的真实世界摘录:

$media = [
    "photos" => [
        ["foo" => "bar", "value" => 10],
        ["foo" => "var", "value" => 20],
        ["foo" => "car", "value" => 50],
    ]
];

echo json_encode($media);
echo "\n\n";

$media["photos"] = array_filter($media["photos"], function($photo) {
    return $photo["value"] > 15;
});

echo json_encode($media); 

输出:

{"photos":[{"foo":"bar","value":10},{"foo":"var","value":20},{"foo":"car","value":50}]}

{"photos":{"1":{"foo":"var","value":20},"2":{"foo":"car","value":50}}}

预期输出:

{"photos":[{"foo":"bar","value":10},{"foo":"var","value":20},{"foo":"car","value":50}]}

{"photos":[{"foo":"var","value":20},{"foo":"car","value":50}]}

数组未从一种类型转换为另一种类型 - 它们在 PHP 中是相同的。只是 array_filter() 在过滤时保留了 key/value 关联。无法自动重新索引数组 according to the documentation,因此您必须手动执行:

$my_arr = array_values(array_filter($my_arr, function($obj) {
    return $obj["value"] < 100;
}));