How to rearrange elements with subordination in an array

Source: Internet
Author: User
Obtain a set of two-dimensional arrays from a data table. Each element has a key value of id and pid. Without recursion, how does one move an element into the corresponding id element based on its pid value to become its child element? {Code...} is rearranged to {code...}, which involves only two layers of hierarchical relationships. Obtain a set of two-dimensional arrays from a data table. Each element has a key value of id and pid. Without recursion, how does one move an element into the corresponding id element based on its pid value to become its child element?

array(6) {  [0] => array(3) {    ["id"]   =>  "21"    ["pid"]  =>  "0"    ["name"] =>  "aaa"  }  [1] => array(3) {    ["id"]   =>  "22"    ["pid"]  =>  "0"    ["name"] =>  "bbb"  }  [2] => array(3) {    ["id"]   =>  "23"    ["pid"]  =>  "0"    ["name"] =>  "ccc"  }  [3] => array(3) {    ["id"]   =>  "24"    ["pid"]  =>  "23"    ["name"] =>  "ddd"  }  [4] => array(3) {    ["id"]   =>  "25"    ["pid"]  =>  "23"    ["name"] =>  "eee"  }  [5] => array(3) {    ["id"]   =>  "26"    ["pid"]  =>  "22"    ["name"] =>  "fff"  }}

Rearrange

array(3) {  [0] => array(3) {    ["id"]   =>  "21"    ["pid"]  =>  "0"    ["name"] =>  "aaa"  }  [1] => array(4) {    ["id"]   =>  "22"    ["pid"]  =>  "0"    ["name"] =>  "bbb"    ["child"]=>  array(1) {            [0] => array(3) {                ["id"]   =>  "26"                ["pid"]  =>  "22"                ["name"] =>  "fff"            }    }  }  [2] => array(4) {    ["id"]   =>  "23"    ["pid"]  =>  "0"    ["name"] =>  "ccc"        ["child"]=>  array(2) {             [0] => array(3) {                ["id"]   =>  "24"                ["pid"]  =>  "23"                ["name"] =>  "ddd"            }            [1] => array(3) {                ["id"]   =>  "25"                ["pid"]  =>  "23"                ["name"] =>  "eee"            }    }  }}

There are only two layers of hierarchical relationships involved.

Reply content:

Obtain a set of two-dimensional arrays from a data table. Each element has a key value of id and pid. Without recursion, how does one move an element into the corresponding id element based on its pid value to become its child element?

array(6) {  [0] => array(3) {    ["id"]   =>  "21"    ["pid"]  =>  "0"    ["name"] =>  "aaa"  }  [1] => array(3) {    ["id"]   =>  "22"    ["pid"]  =>  "0"    ["name"] =>  "bbb"  }  [2] => array(3) {    ["id"]   =>  "23"    ["pid"]  =>  "0"    ["name"] =>  "ccc"  }  [3] => array(3) {    ["id"]   =>  "24"    ["pid"]  =>  "23"    ["name"] =>  "ddd"  }  [4] => array(3) {    ["id"]   =>  "25"    ["pid"]  =>  "23"    ["name"] =>  "eee"  }  [5] => array(3) {    ["id"]   =>  "26"    ["pid"]  =>  "22"    ["name"] =>  "fff"  }}

Rearrange

array(3) {  [0] => array(3) {    ["id"]   =>  "21"    ["pid"]  =>  "0"    ["name"] =>  "aaa"  }  [1] => array(4) {    ["id"]   =>  "22"    ["pid"]  =>  "0"    ["name"] =>  "bbb"    ["child"]=>  array(1) {            [0] => array(3) {                ["id"]   =>  "26"                ["pid"]  =>  "22"                ["name"] =>  "fff"            }    }  }  [2] => array(4) {    ["id"]   =>  "23"    ["pid"]  =>  "0"    ["name"] =>  "ccc"        ["child"]=>  array(2) {             [0] => array(3) {                ["id"]   =>  "24"                ["pid"]  =>  "23"                ["name"] =>  "ddd"            }            [1] => array(3) {                ["id"]   =>  "25"                ["pid"]  =>  "23"                ["name"] =>  "eee"            }    }  }}

There are only two layers of hierarchical relationships involved.

When I want to learn algorithms, I should talk about how to change recursion into loop implementation.
Generally, recursion can be implemented by queue + loop. You should first think about it and write the program with no space.

You are actually implementing this loop. Where do you need recursion ......

I don't have a PHP environment. I will write a file for you using JS.

If I don't understand JS, Do C # and Java understand it? PHP has been lost for too long, and the syntax has been forgotten.

javascriptvar data = [{    "id": "21",    "pid": "0",    "name": "aaa"}, {    "id": "22",    "pid": "0",    "name": "bbb"}, {    "id": "23",    "pid": "0",    "name": "ccc"}, {    "id": "24",    "pid": "23",    "name": "ddd"}, {    "id": "25",    "pid": "23",    "name": "eee"}, {    "id": "26",    "pid": "22",    "name": "fff"}];var map = {}var root = []data.forEach(function(item) {    map[item.id] = item;    var parent = map[item.pid];    if (parent) {        parent.child = parent.child || [];        parent.child.push(item);    } else {        root.push(item);    }});console.log(JSON.stringify(root, null, 4));

Output

[    {        "id": "21",        "pid": "0",        "name": "aaa"    },    {        "id": "22",        "pid": "0",        "name": "bbb",        "child": [            {                "id": "26",                "pid": "22",                "name": "fff"            }        ]    },    {        "id": "23",        "pid": "0",        "name": "ccc",        "child": [            {                "id": "24",                "pid": "23",                "name": "ddd"            },            {                "id": "25",                "pid": "23",                "name": "eee"            }        ]    }]

Thank you for your answers. After reading your answers, you are still digesting them. If the foundation is not solid, you need to learn more.
I have referred to the next-door question. The implementation code is as follows:

$ Arr = array ('id' => 21, 'pid '=> 0, 'name' => 'aaa'), array ('id' => 22, 'pid '=> 0, 'name' => 'bbb'), array ('id' => 23, 'pid '=> 0, 'name' => 'ccc '), array ('id' => 24, 'pid' => 23, 'name' => 'ddd '), array ('id' => 25, 'pid '=> 23, 'name' => 'Eee'), array ('id' => 26, 'pid '=> 22, 'name' => 'fff'),); $ temp = []; foreach ($ arr as $ item) {list ($ id, $ pid, $ name) = array_values ($ item); // retrieve the array value and generate the variable if (array_key_exists ($ pid, $ temp) respectively )) // check whether a key with the same key name as $ pid exists in the temporary array $ temp {$ temp [$ pid] ['child '] [] = array ('id' =>$ id, 'pid '=> $ pid, 'name' => $ name ); // If yes, add the child element named $ pid in the temporary array.} else $ temp [$ id] = array ('id' => $ id, 'pid '=> $ pid, 'name' => $ name ); // if it does not exist, add an array to the temporary array and set the key name to $ id} $ array = array_values ($ temp ); // change the key with $ id as the key name in the temporary array to a digital index echo"
";print_r($array);

The process of generating values for variables is redundant. The foreach part is updated as follows:

foreach ($arr as $item){    if (array_key_exists($item['pid'], $temp))    {               $temp[$item['pid']]['child'][]=$item;    }else        $temp[$item['id']]=$item;}

First calculate the top-level pid of each array, and then sort it.


   $ Current ['pid '], 'Child' => array () ;}} else {if (array_key_exists ($ current ['id'], $ newArr )) {array_merge ($ newArr [$ current ['id'], $ current);} else {$ newArr [$ current ['id'] = $ current ;}} $ current = array_shift ($ arr);} // update the sorting ksort ($ newArr) of arrays and subarrays; foreach ($ newArr as $ arr) {if (array_key_exists ('child ', $ arr) {usort ($ arr ['child'], function ($ a, $ B) {return $ a ['id']> $ B ['id']? 1:-1 ;}) ;}array_push ($ rtnArr, $ arr) ;}// print print_r ($ rtnArr);?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.