我有一个索引数组,它包含一些关联数组,我应用了一个简单的
$my_arr = array_filter($my_arr, function($obj) {
return $obj["value"] < 100;
});
用于过滤数组中的一些项目。
这开始以奇怪的方式使我的Angular前端错误,所以几分钟后我发现$my_arr
正在从索引数组转换为关联数组。
array_filter
中的预期行为吗?array_filter
我想要一个索引数组?编辑:根据评论中的要求,我的$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}]}
答案 0 :(得分:7)
数组没有从一种类型转换为另一种类型 - 它们在PHP中是相同的。只是array_filter()
在过滤时保留了键/值关联。无法自动重新索引数组according to the documentation,因此您必须手动执行:
$my_arr = array_values(array_filter($my_arr, function($obj) {
return $obj["value"] < 100;
}));