dpxnrx11199 2014-03-25 16:41
浏览 296
已采纳

使用PHP创建JSON对象

I have hard time creating the following JSON format using PHP code below. Please suggest.

PHP Code

$postArray = array(
    "MainPage" =>  array(
        "i_date"=> "10-10-2012",
        "i_location"=>$_POST["location-text"],
        "i_summary"=>$_POST["summary-text"],
    "SubPage" => "[" array(
        "first_name"=> $_POST["first-1"],
        "last_name"=>$_POST["last-1"]
         ),
         array(
            "first_name"=>$_POST["first-2"],
        "last_name"=>$_POST["last-2"]
         ) "]"
    )
);


array_push($postArray["MainPage"]["SubPage"], 
    array(
         "first_name"=>$_POST["first-3"],
         "last_name"=>$_POST["last-3"]
    )
);

$json = json_encode( $postArray );

Here is the final ouput I am trying to achieve.

{
  "MainPage":{
    "i_date":"2014-03-20",
    "i_location":"test",
    "i_summary":"test test",
    "SubPage":[
      {
        "first_name":"first name test1",
        "last_name":"last name test1"
      },
      {
        "first_name":"first name test2",
        "last_name":"last name test2"
      },
      {
        "first_name":"first name test3",
        "last_name":"last name test3"
      }
    ]
  }
}
  • 写回答

1条回答 默认 最新

  • dongxilan9351 2014-03-25 17:08
    关注

    I've made some changes to your original code which should give the results that you want.

    $postArray = array(
        'MainPage' => array(
            'i_date' => '2014-03-20',
            'i_location' => $_POST["location-text"],
            'i_summary' => $_POST["summary-text"],
            'SubPage' => array(
                array(
                    'first_name' => $_POST["first-1"],
                    'last_name' => $_POST["last-1"]
                ),
                array(
                    'first_name' => $_POST["first-2"],
                    'last_name' => $_POST["last-2"]
                )                        
            )
        )
    );
    
    $postArray['MainPage']['SubPage'][] = array(
        'first_name' => $_POST["first-3"],
        'last_name' => $_POST["last-3"]
    );
    
    $json = json_encode($postArray);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)