Table of Contents
回复内容:

PHP反向递归

Jun 06, 2016 pm 08:23 PM
php recursion

需求是这样的,原数组如下,通过chrome配合phpview的插件截图(二维数组)
PHP反向递归

经过“反向递归后”需要展现成如下树状结构。
其中parent_id是level为上一级的id(最顶级的level为0),比如parent_id=125的用户level为1,那么他的上一级的id是125,先谢过了
PHP反向递归

回复内容:

需求是这样的,原数组如下,通过chrome配合phpview的插件截图(二维数组)
PHP反向递归

经过“反向递归后”需要展现成如下树状结构。
其中parent_id是level为上一级的id(最顶级的level为0),比如parent_id=125的用户level为1,那么他的上一级的id是125,先谢过了
PHP反向递归

不好意思,回答晚了,做了个稍微复杂点的,用了一个内部排序:

<code>// $formated_arr 是你的输入对象
// 首先按照level做一次排序
usort($formated_arr, function($a, $b) {
    $al = intval($a['level']);
    $bl = intval($b['level']);
    return ($al > $bl) ? 1 : -1;
});

// 因为上面做过排序了,所以这里虽然是递归,但对数组只遍历了一次
function reformat_tree(&$arrTmp, $parent_id=0) {
    $ret = null;
    foreach ($arrTmp as $k => $v) {
        if($v['parent_id'] == $parent_id) {
            $ret[$v['id']] = $v;
            unset($arrTmp[$k]);
            $child = reformat_tree($arrTmp, $v['id']);
            !is_null($child) ? $ret[$v['id']]['child'] = $child : 1;
        }
    }
    return $ret;
}

echo(json_encode(reformat_tree($formated_arr)));</code>
Copy after login

试试我这个:

<code>function createMenuTree($data = array(), $pid = 0){
    if (empty($data)){
        return array();
    }
     static $level = 1;
     $returnArray = array();
    foreach ($data as $node){
        if ($node['parent_id'] == $pid){
            $returnArray[] = array(
                'cat_id'   => $node['cat_id'],
                'cat_name' => $node['cat_name'],
                'level' => $level,
                'parent_id' => $node['parent_id'],
                'show_in_nav' => $node['show_in_nav'],
                'is_show' => $node['is_show'],
                'sort_order' => $node['sort_order']
                );
            if (hasChild($node['cat_id'], $data)){
               $level++;
               $returnArray = array_merge($returnArray, createMenuTree($data, $node['cat_id']));
               $level--;
            }
        }
    }
     return $returnArray;
}

function hasChild($cid, $data){
    $hasChild = false;
    foreach ($data as $node){
        if ($node['parent_id'] == $cid){
            $hasChild = true;
            break;
        }
    }
    return $hasChild;
}
 </code>
Copy after login

字段跟你的不是很一样,但是思路好像跟你想要的差不多,你可以自己拿去修改一下。

<code>function recursive_tree($arr,$level = 0,$parent_id = 0){
    $tmp = array();       
    foreach ($arr as $key => $value) {
        if($value['level'] == $level && $value['parent_id'] == $parent_id){
            $arr[$key]['child'] = recursive_tree($arr,$value['level'] + 1,$value['id']);
            if(empty($arr[$key]['child'])){
                unset($arr[$key]['child']);
            }
            $tmp[] = $arr[$key];
        }
    }
    return $tmp;
}


$arr = array(
    array(
        'id'     => '125',
        'level' => '0',
        'user_id' => '1021',
        'parent_id' => '0', 
    ),
    array(
        'id'     => '189',
        'level' => '1',
        'user_id' => '1022',
        'parent_id' => '125', 
    ),
    array(
        'id'     => '425',
        'level' => '2',
        'user_id' => '4119',
        'parent_id' => '189', 
    ),
    array(
        'id'     => '385',
        'level' => '3',
        'user_id' => '3170',
        'parent_id' => '425', 
    ),
    array(
        'id'     => '782',
        'level' => '3',
        'user_id' => '5698',
        'parent_id' => '425', 
    ),
    array(
        'id'     => '688',
        'level' => '1',
        'user_id' => '7045',
        'parent_id' => '125', 
    )
);

echo json_encode(recursive_tree($arr,0,0));die;</code>
Copy after login

http://segmentfault.com/q/1010000004052822/a-1020000004055246

参照我在这个问题下的回答的前半部分,详细解释了题主的问题所需要的那个并不复杂的算法,只是题目从OC变成了PHP。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

See all articles