在PHP中为Web服务创建嵌套数组

时间:2014-10-04 04:45:38

标签: php arrays

首先,我是PHP的初学者,所以请耐心等待。

我想创建类似这个JSON数组的东西:

{
children: [
{
id: "1"
user_id: "1"
name: "Test"
gender: "M"
born_date: "2014-10-01"
born_hour: "12:12:12"
hospital: "test hospital"
}-
}-
{
id: "2"
user_id: "1"
name: "test2"
gender: "F"
born_date: "2014-10-06"
born_hour: null
hospital: null
}-
]
result: "true"
total: 2
}

为了让我的问题更容易,这是一个我想要创建的易于阅读的JSON(你可以认为手机作为孩子在我的情况下):

enter image description here

children应该成为父级和数组。这就是我到目前为止所取得的成就:

{
0: {
children: {
id: "1"
user_id: "1"
name: "Test"
gender: "M"
born_date: "2014-10-01"
born_hour: "12:12:12"
hospital: "test hospital"
}-
}-
1: {
children: {
id: "2"
user_id: "1"
name: "test2"
gender: "F"
born_date: "2014-10-06"
born_hour: null
hospital: null
}-
}-
result: "true"
total: 2
}

子项不是项目的父项,不在数组([])中。

这是我生成上述JSON的代码:

$resultArray = array('result' => 'true', 'total' => $size);

            foreach($result as $child)
            {
                if($child)
                {
                    //add to array
                    $resultArray[] = array('children' => array('id' => $child['id'], 
                    'user_id' => $child['user_id'], 
                    'name' => $child['name'], 
                    'gender' => $child['gender'],
                    'born_date' => $child['born_date'], 
                    'born_hour' => $child['born_hour'],
                    'hospital' => $child['hospital']));
                }
            }

            $this->response($resultArray, 200);

请帮助我。谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

你可以先建立数组,推送所有项目等。然后最后把那个父键放在最后,把收集到的数组放在那里:

foreach($result as $child) {
    if($child) {
        // so build it first
        $resultArray[] = array(
            'id' => $child['id'], 
            'user_id' => $child['user_id'], 
            'name' => $child['name'], 
            'gender' => $child['gender'],
            'born_date' => $child['born_date'], 
            'born_hour' => $child['born_hour'],
            'hospital' => $child['hospital']
        );
    }
}
// end then finally, put it inside the parent key children
$resultArray = array('result' => 'true', 'total' => $size, 'children' => $resultArray);
$this->response($resultArray, 200);

答案 1 :(得分:1)

您可以使用'json_encode'功能。

$resultArray = json_encode($result);

http://php.net/manual/en/function.json-encode.php