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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法