Converts the returned dataset to an array tree.

Source: Internet
Author: User
Converts the returned dataset to an array tree.
For example
$ Old = array (
Array ('id' => 1, 'pid '=> 0, 'name' => '1e '),
Array ('id' => 2, 'pid '=> 1, 'name' => 'second '),
Array ('id' => 3, 'pid '=> 2, 'name' => 'third '),
);
Print_r (list_to_tree ($ old, 'id', 'pid ',' _ child '));
Output:
$ Old = array (
Array (
'Id' => 1,
'Pid '=> 0,
'Name' => '1 ',
'_ Child' => array (
'Id' => 2,
'Pid '=> 1,
'Name' => 'second'
'_ Child' => array ('id' => 3, 'pid '=> 2, 'name' => 'third '),
),
),

);

  1. /**
  2. * Convert the returned dataset to a Tree.
  3. * @ Access public
  4. * @ Param array $ list the dataset to be converted
  5. * @ Param string $ pid parent tag field
  6. * @ Param string $ level field
  7. * @ Return array
  8. */
  9. Function list_to_tree ($ list, $ pk = 'id', $ pid = 'pid', $ child = '_ child', $ root = 0 ){
  10. // Create a Tree
  11. $ Tree = array ();
  12. If (is_array ($ list )){
  13. // Create a primary key-based array reference
  14. $ Refer = array ();
  15. Foreach ($ list as $ key => $ data ){
  16. $ Refer [$ data [$ pk] = & $ list [$ key];
  17. }
  18. Foreach ($ list as $ key => $ data ){
  19. // Determine whether a parent exists
  20. $ ParentId = $ data [$ pid];
  21. If ($ root = $ parentId ){
  22. $ Tree [] = & $ list [$ key];
  23. } Else {
  24. If (isset ($ refer [$ parentId]) {
  25. $ Parent = & $ refer [$ parentId];
  26. $ Parent [$ child] [] = & $ list [$ key];
  27. }
  28. }
  29. }
  30. }
  31. Return $ tree;
  32. }

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.