如何在 php 中创建嵌套的 JSON 对象?

在 PHP 中定义这种 JSON 对象的正确方法是什么


  [

    {

        "id": 1111,

        "tahun": 2019,

        "nilai": 9123,

        "detail": [

            {

              "id": 0,

              "nilai": 0

            }

        ]

    }

  ]

我需要创建一个嵌套数组,该数组将通过json_encode()转换为JSON对象


class Service {

    public $id = 1111;

    public $tahun = 2019;

    public $nilai = 9123;

    public $detail = array();


    function  __construct(){

        for ( $i=3; $i-->0;){

            array_push($this->detail, new Detail);

        }

    }

}


class Detail {

    public $id = 1;

    public $nilai = 2000;

}

echo '<pre>';

echo json_encode([new Service],JSON_PRETTY_PRINT);

echo '</pre>';

如何在不使用类的情况下创建这样的输出?


慕无忌1623718
浏览 118回答 3
3回答

海绵宝宝撒

您只需要创建多阵列,并且根据您知道必须使用json_encode$array = array("id" => "1111",&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "tahun" => "tahun",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "detail" => array( array( "id" => "0", "nilai" => "0" ) )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );echo json_encode( $data = array( $array ));

慕运维8079593

您可以定义一个内部有数组的数组。json_encode(array('a' => 1, 'b' => 2, 'c'=>array('a1'=>1, 'b2'=>2), 'd' => 4, 'e' => 5);使用json_encode()你会得到{&nbsp; &nbsp; &nbsp; &nbsp; "a": 1,&nbsp; &nbsp; &nbsp; &nbsp; "b": 2,&nbsp; &nbsp; &nbsp; &nbsp; "c":&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "a1": 1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "b1": 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; "d"=>4,&nbsp; &nbsp; &nbsp; &nbsp; "e"=>5}与回声它出来放这个{“a”:1,“b”:2,“c”:{“a1”:1,“b2”:2},“d”:4,“e”:5}

郎朗坤

通过简单的嵌套数组&nbsp; &nbsp;$json_array = array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "id"=> 1111,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "tahun" => 2019,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "nilai"=> 9123,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "detail" => array(array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "id" => 0,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "nilai" => 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ) )&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; echo json_encode($json_array);
打开App,查看更多内容
随时随地看视频慕课网APP