【问题标题】:Processing multidimensional array in php and send to json在php中处理多维数组并发送到json
【发布时间】:2018-03-20 10:16:53
【问题描述】:

我有带有字段的 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']
    );
}

如何向这个数组元素中添加“子元素”,其中所有元素都将与相同的“父元素”进行整理? 谢谢!

【问题讨论】:

    标签: php arrays json multidimensional-array


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2018-09-29
      • 2015-01-31
      • 2017-03-27
      • 2018-05-23
      • 1970-01-01
      • 2015-09-26
      相关资源
      最近更新 更多