Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/244.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否可以将json_encode()作为数组而不是对象返回,这样我就可以轻松地使用`.filter()`或`.forEach()`方法_Javascript_Php_Ecmascript 6 - Fatal编程技术网

Javascript 是否可以将json_encode()作为数组而不是对象返回,这样我就可以轻松地使用`.filter()`或`.forEach()`方法

Javascript 是否可以将json_encode()作为数组而不是对象返回,这样我就可以轻松地使用`.filter()`或`.forEach()`方法,javascript,php,ecmascript-6,Javascript,Php,Ecmascript 6,我只是想确定没有这样的事情。。。因为我找不到任何提到这一点的东西: 目前,当我使用json\u encode($array)时,我会得到一个json对象,如下所示: { "1": {"user_id":1,"test":"","user_name":"potato0","isok":"true"}, "2":{"user_id":2,"test":"","user_name":"potato1","isok":" true"}, "3":{"user_id":3,"t

我只是想确定没有这样的事情。。。因为我找不到任何提到这一点的东西:

目前,当我使用
json\u encode($array)
时,我会得到一个json对象,如下所示:

{
    "1": {"user_id":1,"test":"","user_name":"potato0","isok":"true"},

    "2":{"user_id":2,"test":"","user_name":"potato1","isok":" true"},

    "3":{"user_id":3,"test":"","user_name":"potato2","isok":" true"},

    "4":{"user_id":4,"test":"","user_name":"potato3","isok":"locationd"}
}
我想运行
.filter()
/
.forEach()
方法

但它们不会在对象(
{…}
)上运行,而是在数组(
[…]
)上运行

编辑:似乎不确定我得到了什么,所以这是一个真正的var_dump和json_encode()示例:

变量转储($数组)

echo json_encode(['status'=>true,'data'=>$fruits])

返回的json被定义为“对象”(使用
typeof
检查)


**我不愿意将我的对象转换为js端的数组,我知道这个“技巧”,我更喜欢从php获取json数组作为数组,请关注我的问题**

您需要将主对象更改为数组。我想下面的代码就是你要找的

你的意见:

 var data = {
    "1": {"user_id":1,"test":"","user_name":"potato0","isok":"true"},

    "2":{"user_id":2,"test":"","user_name":"potato1","isok":" true"},

    "3":{"user_id":3,"test":"","user_name":"potato2","isok":" true"},

    "4":{"user_id":4,"test":"","user_name":"potato3","isok":"locationd"}
};
将对象转换为数组

 var result = Object.keys(data).map(function(key) {
  return data[key];
});
现在,您可以对转换后的阵列使用过滤器

var filtered = result.filter(row => { return row.user_id > 1; });
过滤结果为:

[{
"user_id": 2,
"test": "",
"user_name": "potato1",
"isok": " true"
},{
"user_id": 3,
"test": "",
"user_name": "potato2",
"isok": " true"
},{
"user_id": 4,
"test": "",
"user_name": "potato3",
"isok": "locationd"
}]

希望这就是您正在寻找的,这里是正在使用的演示链接:

您的
$array
看起来是1索引的,不是0索引的,不懂PHP,但这看起来不太有希望
Object.values(…)
@Snow您能简单解释一下吗?请添加phpscript@wellhellothere:然后必须创建数组而不是对象
var filtered = result.filter(row => { return row.user_id > 1; });
[{
"user_id": 2,
"test": "",
"user_name": "potato1",
"isok": " true"
},{
"user_id": 3,
"test": "",
"user_name": "potato2",
"isok": " true"
},{
"user_id": 4,
"test": "",
"user_name": "potato3",
"isok": "locationd"
}]