Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.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
Php 如何使用json_encode操作输出?_Php_Json - Fatal编程技术网

Php 如何使用json_encode操作输出?

Php 如何使用json_encode操作输出?,php,json,Php,Json,如何构造$array,以便在将其传递给 产出将是: $output = [ {apples:"33" ,oranges:"22"}, {apples:"44" ,oranges:"11"}, {apples:"55" ,oranges:"66"}, ] 我需要使用哪些选项来获得所需的输出?或者这一切都是关于我如何构造我的PHP数组的?这应该适合您: []=数组 {}=对象 键:值=键:值 您只需要将一个关联数组传递给json_encode $array = array (

如何构造
$array
,以便在将其传递给

产出将是:

$output = [
  {apples:"33" ,oranges:"22"},
  {apples:"44" ,oranges:"11"},
  {apples:"55" ,oranges:"66"},
]

我需要使用哪些选项来获得所需的输出?或者这一切都是关于我如何构造我的PHP数组的?

这应该适合您:

  • []
    =数组
  • {}
    =对象
  • 键:值
    =键:值

您只需要将一个关联数组传递给json_encode

$array = array (
    array(
        'apples'=>'33',
        'oranges'=>'22'
    ),
    array(
        'apples'=>'44',
        'oranges'=>'11'
    ),
    array(
        'apples'=>'55',
        'oranges'=>'66'
    )
);

您可以在
json\u encode($var)
中传递关联数组数组


))

json\u enocde
??您的意思可能是
json\u encode
?不需要强制转换到对象,因为json没有索引数组,所以任何索引的PHP数组都将以json作为对象呈现。@TRiG Yes,但我想清楚地表明
{}
是json中的对象
<?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"
    }
]
$array = array (
    array(
        'apples'=>'33',
        'oranges'=>'22'
    ),
    array(
        'apples'=>'44',
        'oranges'=>'11'
    ),
    array(
        'apples'=>'55',
        'oranges'=>'66'
    )
);
$array = array (
array(
    'johan'=>'male',
    'age'=>'22'
),
array(
    'lucy'=>'female',
    'age'=>'24'
),
array(
    'donald'=>'male',
    'age'=>'28'
)