Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

using php to display hierarchical data for use in javascript..

Posted on 2009-07-08
7
301 Views
Last Modified: 2013-12-13
Hi there, I am storing hierarchical data in my mysql database using the method described here:
http://www.sitepoint.com/article/hierarchical-data-database/2/

However i am trying to do something slightly different when the data is extracted as i want php to output the information in the format shown below so i can use the data in a javascript widget i found. At the moment my php function creates an array with all the subordinate data and then it can be reached like so:

$treeinfo = display_tree(1);

foreach($treeinfo as $row) {
                           $row['zone_ID'];
                        $row['zone_Parent_ID'];
                        $row['nright'];
                        $row['nleft'];
                        $row['zone_Name'];
                        $row['zone_indent']; //depth of zone
                        $row['descendants']; //number of child zones
}

Can someone have a pop at doing this because ive been trying for hours and my head is now spinning! Thanks a bunch
var treeData = [
		{title: "Web & Programming", isFolder: true, key: "ZONE_ID",
			children: [
				{title: "PHP",
					children: [
						{title: "PHP 4", key: "zone_ID" },
						{title: "PHP 5", key: "zone_ID" }
					]
				},
				{title: "Sub-item 3.2",
					children: [
						{title: "Sub-item 3.2.1", key: "id3.2.1" },
						{title: "Sub-item 3.2.2", key: "id3.2.2" }
					]
				}
			]
		},
		{title: "Design & Multimedia", isFolder: true, key: "ZONE_ID",
			children: [
				{title: "Flash",
					children: [
					]
				},
				{title: "Photoshop",
					children: [
						{title: "Sub-item 3.2.2", key: "id3.2.2" }
					]
				}
			]
		},
	];

Open in new window

0
Comment
Question by:cookiejest
  • 5
  • 2
7 Comments
 
LVL 1

Expert Comment

by:deefjuh
ID: 24808299
Could you post some testdata?

I have made some recursive functions i'd like to test.
0
 

Author Comment

by:cookiejest
ID: 24808722
sure, here is sql for the data im using to test, if you need it in another format then i can provide it,

it should be a structure like so:

Webofwork
       Web Design
              Flash
                    actionscript
              PHP
              AJAX
       Tax Guidence

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
 
--
-- Database: `webofworkdb`
--
 
-- --------------------------------------------------------
 
--
-- Table structure for table `zones`
--
 
CREATE TABLE IF NOT EXISTS `zones` (
  `zone_ID` int(11) NOT NULL AUTO_INCREMENT,
  `zone_Name` varchar(45) NOT NULL,
  `zone_Description` text NOT NULL,
  `zone_Parent_ID` int(11) DEFAULT NULL,
  `nleft` int(11) DEFAULT NULL,
  `nright` int(11) DEFAULT NULL,
  `nlevel` int(11) DEFAULT NULL,
  `zone_Date_Added` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`zone_ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COMMENT='zones within the database' AUTO_INCREMENT=10 ;
 
--
-- Dumping data for table `zones`
--
 
INSERT INTO `zones` (`zone_ID`, `zone_Name`, `zone_Description`, `zone_Parent_ID`, `nleft`, `nright`, `nlevel`, `zone_Date_Added`) VALUES
(1, 'Web Of Work', 'All the cats in web of work', NULL, 1, 16, NULL, '2009-07-03 14:42:33'),
(2, 'Web Design', 'Stuff about webdesign', 1, 2, 11, NULL, '2009-07-03 14:42:33'),
(3, 'Finance and Management', 'hbhggv', 1, 12, 15, NULL, '2009-07-03 14:47:14'),
(4, 'flash', '', 2, 3, 6, NULL, '2009-07-03 14:48:06'),
(6, 'Tax Guidence', 'stuff about tax', 3, 13, 14, NULL, '2009-07-03 15:54:45'),
(7, 'actionscript', '', 4, 4, 5, NULL, '2009-07-04 11:02:20'),
(8, 'php', 'all about php', 2, 7, 8, NULL, '2009-07-08 22:36:19'),
(9, 'ajax', 'all about ajax', 2, 9, 10, NULL, '2009-07-08 22:36:19');

Open in new window

0
 

Author Comment

by:cookiejest
ID: 24808754
Sorry ive just realised an error, the mysql i gave you is for data that would look like this:

Webofwork
       Web Design
              Flash
                    actionscript
              PHP
              AJAX
       Finance and Management
             Tax Guidence
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 1

Accepted Solution

by:
deefjuh earned 500 total points
ID: 24815143
I have not so much time left, but I have something worked out for ya.

Basically what you need to do is loop through the $treeinfo, and place them under their parent.
Obviously, the one without a parent are toplevel.
 while looping through treeinfo, you set up a new array ($aOrganisedTree), in which you make the basic layout for te output: an multi-dimensional array which resembles the final output.


This looping needs to be recursive as an item might need to be under his parent, which might not exist yet.

So when you can place a child under his parent, be sure to unset it in the array.

The above assumes the parent will (and thus must) exist in order to finish the loop.

The arraysearch function is to search the organised array and returns the path:
It then will be easy to set the child.

When you have the final lay-out in array form,
you need to make a recursive function in which you will struct the string (with "\n" to make newlines).


Good luck!

I might have some time later this evening or tomorrow, but don't count on it.

print_r(ReOrderArray($treeinfo));
//DS: first prep the array to a proper multi-dimensional array
function ReOrderArray($treeinfo){
		$aOrganisedTree = array();
		
		
		//DS: make top-level (the ones without a parent)
		foreach($treeinfo as $key=>$row) {
							$row['zone_ID'];
							$row['zone_Parent_ID'];
							$row['nright'];
							$row['nleft'];
							$row['zone_Name']; //title
							$row['zone_indent']; //depth of zone
							$row['descendants']; //number of child zones
			if(!isset($row['zone_Parent_ID']) ||$row['zone_Parent_ID']== ''){ //DS: top level
				$aOrganisedTree[$key] = $row;
				unset($treeinfo);
			}
		}
		PlaceChildren($treeinfo, &$aOrganisedTree);
	return $aOrganisedTree;
}
 
function PlaceChildren($treeinfo, $aOrganisedTree){
    while(!empty($treeinfo)){
		LoopThroughArr(treeinfo, &$aOrganisedTree);
	}
}
 
function LoopThroughArr($array, $aOrganisedTree){
	
	foreach($array as $key => $value){
		
	}
	return $arrResult;
}
 
//DS: search for id and return the path to it.
function array_searchRecursive( $needle, $haystack, $strict=false, $path=array()){
    if( !is_array($haystack) ) {
        return false;
    }
     foreach($haystack as $key => $val ) {
        if( is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path) ) {
            $path = array_merge($path, array($key), $subPath);
            return $path;
        } elseif( (!$strict && $val == $needle) || ($strict && $val === $needle) ) {
            $path[] = $key;
            return $path;
        }
    }
    return false;
}

Open in new window

0
 

Author Comment

by:cookiejest
ID: 24821074
thank you for replying! I am geteting these errors:

Warning: Call-time pass-by-reference has been deprecated in C:\wamp\www\webofwork.com\new_project.php on line 109

Warning: Call-time pass-by-reference has been deprecated in C:\wamp\www\webofwork.com\new_project.php on line 115

Parse error: parse error, expecting `T_VARIABLE' or `'$'' in C:\wamp\www\webofwork.com\new_project.php on line 144
0
 

Author Comment

by:cookiejest
ID: 24821124
right ive modified the code to remove those errors and its not throwing up anything else, im still not sure how to get from this stage to my final output..
print_r(ReOrderArray($treeinfo));
//DS: first prep the array to a proper multi-dimensional array
function ReOrderArray($treeinfo){
                $aOrganisedTree = array();
                
                
                //DS: make top-level (the ones without a parent)
                foreach($treeinfo as $key=>$row) {
                                                        $row['zone_ID'];
                                                        $row['zone_Parent_ID'];
                                                        $row['nright'];
                                                        $row['nleft'];
                                                        $row['zone_Name']; //title
                                                        $row['zone_indent']; //depth of zone
                                                        $row['descendants']; //number of child zones
                        if(!isset($row['zone_Parent_ID']) ||$row['zone_Parent_ID']== ''){ //DS: top level
                                $aOrganisedTree[$key] = $row;
                                unset($treeinfo);
                        }
                }
                PlaceChildren($treeinfo, $aOrganisedTree);
        return $aOrganisedTree;
}
 
function PlaceChildren($treeinfo, $aOrganisedTree){
    while(!empty($treeinfo)){
                LoopThroughArr(treeinfo, $aOrganisedTree);
        }
}
 
function LoopThroughArr($array, $aOrganisedTree){
        
        foreach($array as $key => $value){
                
        }
        return $arrResult;
}
 
//DS: search for id and return the path to it.
function array_searchRecursive( $needle, $haystack, $strict=false, $path=array()){
    if( !is_array($haystack) ) {
        return false;
    }
     foreach($haystack as $key => $val ) {
        if( is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path) ) {
            $path = array_merge($path, array($key), $subPath);
            return $path;
        } elseif( (!$strict && $val == $needle) || ($strict && $val === $needle) ) {
            $path[] = $key;
            return $path;
        }
    }
    return false;
}

Open in new window

0
 

Author Closing Comment

by:cookiejest
ID: 31601208
had a few issues but got it working!
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
PHP curl issue VERBOSE output 18 88
display balance of stars as greyed out 8 23
Output in PHP throwing alignment of data off issue 12 43
Wordpress Security 29 48
This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question