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 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作