如何构建$array
以便将其传递给json_encode
$output = json_encode($array);
输出将是:
$output = [
{apples:"33" ,oranges:"22"},
{apples:"44" ,oranges:"11"},
{apples:"55" ,oranges:"66"},
]
我需要使用任何选项来获得我需要的输出吗?或者这就是我如何构建我的PHP数组?
答案 0 :(得分:3)
这应该适合你:
[]
= array {}
= object key:value
= key:value
<?php
$array = [
(object)["apples" => "33", "oranges" => "22"],
(object)["apples" => "44", "oranges" => "11"],
(object)["apples" => "55", "oranges" => "66"],
];
echo $output = json_encode($array);
?>
输出:
[
{
"apples": "33",
"oranges": "22"
},
{
"apples": "44",
"oranges": "11"
},
{
"apples": "55",
"oranges": "66"
}
]
答案 1 :(得分:2)
您只需要将一组关联数组传递给json_encode
$array = array (
array(
'apples'=>'33',
'oranges'=>'22'
),
array(
'apples'=>'44',
'oranges'=>'11'
),
array(
'apples'=>'55',
'oranges'=>'66'
)
);
答案 2 :(得分:-1)
你可以在json_encode($var)
中传递一组关联数组。
$array = array (
array(
'johan'=>'male',
'age'=>'22'
),
array(
'lucy'=>'female',
'age'=>'24'
),
array(
'donald'=>'male',
'age'=>'28'
)
);