drll42469 2010-05-09 23:23
浏览 38

如何从db表,php数组或JSON中获取分层php结构[重复]

Possible Duplicate:
Turn database result into array

Hi guys, can you please help me. How to get an hierarchical php structure from a db table, in php array, or JSON, but with the following format:

[
  {
     "attributes":{
        "id":"111"
     },
     "data":"Some node title",
     "children":[
        {
           "attributes":{
              "id":"555"
           },
           "data":"A sub node title here"
        }
     ],
     "state":"open"
  },
  {
     "attributes":{
        "id":"222"
     },
     "data":"Other main node",
     "children":[
        {
           "attributes":{
              "id":"666"
           },
           "data":"Another sub node"
        }
     ],
     "state":"open"
  }
]

My SQL table contains the fields: ID, PARENT, ORDER, TITLE

Can you please help me with this? I'm going crazy trying to get this.

Many thanks in advance. Daniel

  • 写回答

2条回答 默认 最新

  • dpba63888 2010-05-10 03:12
    关注

    Two pass foreach does the trick. This will link all child to their parents recursively.

    $structure = array();
    foreach( $array as $row ) { //add rows to array by id
        $structure[ $row["id"] ] = $row + array( "children" => array() );
    }
    foreach( $structure as &$row ) { //link children to parents
        if( ! is_null( $row["parent"] ) ) {
            $structure[ $row["parent"] ]["children"][] =& $row;    
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线