PHP two-dimensional array converted to a tree-like array

Source: Internet
Author: User

<?php
/**
* @param array $list The result set to convert
* @param string $pid the parent tag field
* @param string $level level Tag field
*/
function List_to_tree ($list, $PK = ' id ', $pid = ' pid ', $child = ' Listarea ', $root = 0) {
Create Tree
$tree = Array ();

if (Is_array ($list)) {
Creating an array reference based on a primary key
$refer = Array ();

foreach ($list as $key = = $data) {
$refer [$data [$pk]] = & $list [$key];
}

foreach ($list as $key = = $data) {
Determine if there is a parent
$parantId = $data [$pid];

if ($root = = $parantId) {
$tree [] = & $list [$key];
} else {
if (Isset ($refer [$parantId])) {
$parent = & $refer [$parantId];
$parent [$child] = & $list [$key];
}
}
}
}

return $tree;
}

$arr = Array (
The array (' ID ' =>1, ' pid ' =>0, ' name ' = ' UrlEncode ' (' Dalian '), ' code ' = ' dd ', ' listarea ' = = = Array ()),
Array (' ID ' =>2, ' pid ' =>1, ' name ' = ' UrlEncode ' (' Hong Kong '), ' code ' = ' dd ', ' listarea ' = = = Array ()),
The array (' ID ' =>4, ' pid ' =>3, ' name ' = = ' m ', ' code ' = ' dd ', ' listarea ' = = Array ()),
Array (' ID ' =>2, ' pid ' =>1, ' name ' = = ' gg ', ' code ' = ' AA ', ' listarea ' = = Array ()),
Array (' ID ' =>3, ' pid ' =>1, ' name ' = ' e ', ' code ' = ' dd ', ' listarea ' = = Array ())
);
$array = array (' ID ' =>0, ' pid ' =>0, ' name ' = ' national '));
$array 2 = Array_merge ($array, $arr);
Array_push ($arr, $array);

Print_r ($array); exit;

$tree = List_to_tree ($arr);
echo Json_encode ($tree);

Note: Objects that do not have child nodes are not displayed

PHP two-dimensional array converted to a tree-like array

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.