我希望json_encode返回类似这样的内容
[{key: "value"},{key:"value"},...]
相反,我得到这样的东西:
{"1": {key: "value"}, "2": {key: "value"}, ...}
结果很好,直到我做了
array_filter
...奇怪...function somefunction($id, $ignore = array()) {
$ignorefunc = function($obj) use ($ignore) {
return !in_array($obj['key'], $ignore);
};
global $db;
$q = "Some query";
$rows = $db->giveMeSomeRows();
$result = array();
if ($rows) {
// this mapping I've always done
$result = array_map(array('SomeClass', 'SomeMappingFunction'), $rows);
if (is_array($ignore) && count($ignore) > 0) {
/////// PROBLEM AFTER THIS LINE ////////
$result = array_filter($result, $ignorefunc);
}
}
return $result;
}
再说一次,如果我注释掉
array_filter
,那么无论json_encode
返回什么,我都会从somefunction
中得到想要的东西,如果没有,我会得到一个JSON-Object。如果我在
var_dump
之前和之后$result
array_filter
,则它是同一类型的PHP数组,键中没有字符串,依此类推。 最佳答案
您需要一个array
,但您正在获取json
对象,因为您的数组不是从0
开始的,请尝试使用array_values
重置该数组
例子
$arr = array(1=>"a",2=>"Fish");
print(json_encode($arr));
print(json_encode(array_values($arr)));
输出
{"1":"a","2":"Fish"}
["a","Fish"]
代替
$result = array_filter($result, $ignorefunc);
和
$result = array_filter($result, $ignorefunc);
$result = array_values($result);
关于php - json_encode在array_filter之后具有不同的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15833720/