array( "food"=>array( "Nasi Padang", -6ren">
gpt4 book ai didi

javascript - 解码json时保持关联数组

转载 作者:可可西里 更新时间:2023-10-31 23:37:08 24 4
gpt4 key购买 nike

例如我有以下数组:-

$menu = array(
"result"=>array(
"food"=>array(
"Nasi Padang",
"Kentang Goreng",
"Potato Wedges"
),
"drink"=>array(
"Bajigur",
"AO",
"Sabun"
)
)
);

使用 json_encode 上面的代码变成:-

{
"result":{
"food":[
"Nasi Padang",
"Kentang Goreng",
"Potato Wedges"
],
"drink":[
"Bajigur",
"AO",
"Sabun"
]
}
}

如您所见,result 数组变成了一个对象,而不是保持数组的形式,这可能是因为 JavaScript 没有开箱即用的关联数组。

那么,是否可以将结果(在执行json_decode 之后)视为数组而不像(array) 那样进行任何转换?

编辑:回应 Anant 回复/评论,我在我的本地主机中尝试了以下代码

$test = new stdClass;
$test->count = 1337;
$test->page = 2;

$menu = array(
"test"=>$test,
"result"=>array(
"food"=>array(
"Nasi Padang",
"Kentang Goreng",
"Potato Wedges"
),
"drink"=>array(
"Bajigur",
"AO",
"Sabun"
)
)
);

$json = json_encode($menu);
echo print_r(json_decode($json, true));

结果

Array
(
[test] => Array
(
[count] => 1337
[page] => 2
)

[result] => Array
(
[food] => Array
(
[0] => Nasi Padang
[1] => Kentang Goreng
[2] => Potato Wedges
)

[drink] => Array
(
[0] => Bajigur
[1] => AO
[2] => Sabun
)

)

)

最佳答案

As you can see, result array become an object instead of stay in form of array, maybe this is because JavaScript doesn't have an associative array out of the box.

这是因为在 JSON 中,普通对象的作用与 PHP 中的关联数组相同。唯一的区别是它不是有序的。

JSON 没有具有同样有序的命名属性的数据结构。为此,您需要使用一组对象,例如:

[
{ "name" : "foo", "value" : 1 },
{ "name" : "bar", "value" : 2 }
]

so, is there anyway to treat the result (after doing json_decode) as array without any casting like (array)?

来自 the manual :

assoc: When TRUE, returned objects will be converted into associative arrays.

所以设置json_decode的第二个参数为true

关于javascript - 解码json时保持关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42060787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com