在php中处理多维数组并发送到json

时间:2018-03-20 10:16:54

标签: php arrays json multidimensional-array

我的mysql表包含字段:

id | building | title | parent

我想通过fullcalendar.io创建时间线日历。

我需要创建这个:

{ id: '1', building: '460 Bryant', title: 'Auditorium D', children: [
   { id: '2', title: 'Room D1' },
    { id: '3', title: 'Room D2' }
 ] }, etc...

我这样做了:

$query = "SELECT * FROM resources ORDER BY id";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();

foreach($result as $row)
{
    $data[] = array(
        'id'       => $row['id'],
        'building' => $row['building'],
        'title'    => $row['title']
    );
}

如何添加到此数组元素" children"其中所有元素将与相同的父母一起进行整理#? 谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用id作为数组的键,并使用它来存储父元素中的子值:

foreach($result as $row)
{
    $id = $row['id'] ;
    $id_parent = $row['parent'] ;

    if ($id_parent)
    {
        $data[$id_parent]['children'][] = array(
            'id'       => $id,
            'title'    => $row['fname']
        );
    }
    else
    {
        $data[$id] = array(
            'id'       => $id,
            'building' => $row['building'],
            'title'    => $row['fname']
        );
    }
}

// reset indices :
$data = array_values($data);

// create the JSON:
echo json_encode($data);