微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从该结果集中创建一个数组嵌套的类别存储在遍历模型中的数据库中?

如何解决如何从该结果集中创建一个数组嵌套的类别存储在遍历模型中的数据库中?

啊,最后有一些参考文献很方便:

<?PHP
$tree = array(
    array('Cat 1', 'depth' => 0),
    array('Cat 2', 'depth' => 1),
    array('Cat 3', 'depth' => 1),
    array('Cat 4', 'depth' => 2),
    array('Cat 5', 'depth' => 1),
    array('Cat 6', 'depth' => 2),
    array('Cat 7', 'depth' => 3),
    array('Cat 8', 'depth' => 1)
);
//same as before
$currDepth = -1;

//initilialize result
$result = array();

//create path structure for depths
$path = array();

//create 'root' node
$olditem = array('children'=> &$result);


foreach($tree as $item){
    if($item['depth'] > $currDepth){
        //remove possible old reference (old depth of other branch
        if(isset($path[$item['depth']])) unset($path[$item['depth']]);

        //make sure we have an array entry
        if(!isset($olditem['children'])) $olditem['children'] = array();

        //acquire target
        $path[$item['depth']] = &$olditem['children'];
    }
    if($item['depth'] != $currDepth) unset($olditem);
    //set correct target
    $currDepth = $item['depth'];
    //add item
    $path[$currDepth][] = &$item;
    //copy & remove reference
    $olditem = &$item;
    unset($item);
}
//always nice to clean up reference bombs:
unset($path);
unset($olditem);

var_dump($result);
?>

解决方法

逻辑波纹管用于构建有序列表,但是如何对数组执行相同操作?

我想建立一个嵌套数组。

// bootstrap loop
$result = '';
$currDepth = -1;  // -1 to get the outer <ul>
while (!empty($tree)) {
  $currNode = array_shift($tree);
  // Level down?
  if ($currNode['depth'] > $currDepth) {
    // Yes,open <ul>
    $result .= '<ul>';
  }
  // Level up?
  if ($currNode['depth'] < $currDepth) {
    // Yes,close n open <ul>
    $result .= str_repeat('</ul>',$currDepth - $currNode['depth']);
  }
  // Always add node
  $result .= '<li>' . $currNode['title'] . '</li>';
  // Adjust current depth
  $currDepth = $currNode['depth'];
  // Are we finished?
  if (empty($tree)) {
    // Yes,$currDepth + 1);
  }
}

print $result;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。