Bookmark and Share

Using PHP Variable Variable.

Posted: Friday, March 27th, 2009 at 2:30 pmUpdated: Friday, March 27th, 2009 at 2:30 pm

Using PHP variable variable to solve the problem

If you’re selecting the data from a table on database, chances are you’ll end up with a data array similar to the one below. To shorten the post, I’ll just put the first 2 rows.

$cat[0]['category_id'] = 1; 
$cat[0]['parent_id'] = 0;
$cat[0]['name'] = 'Electronics';

$cat[1]['category_id'] = 2;
$cat[1]['parent_id'] = 1; 
$cat[1]['name'] = 'Audio';

Rather than elaborating in long words about what and how PHP variable variable can be used to solve the problem, I thought it’s easier to give you the code directly. Take a look at the code below and I think it’s rather clear on how useful PHP variable variable in simplifying this particular problem.

$xml_0 = new SimpleXMLElement('<response />');

$skipped_categories = array();
foreach ($cat as $c) {
	$parent_xml = 'xml_' . $c['parent_id'];
	$node_xml	= 'xml_' . $c['category_id'];

	if (!isset($$parent_xml)) {
		$skipped_categories[] = $c;
	} else {
		$$node_xml = $$parent_xml->addChild('item');
		$$node_xml->addAttribute('id', $c['category_id']);
		$$node_xml->addAttribute('name', $c['name']);
	}
}

if (!empty($skipped_categories)) {
	foreach ($skipped_categories as $c) {
		$parent_xml = 'xml_' . $c['parent_id'];
		$node_xml	= 'xml_' . $c['category_id'];

		if (!isset($$parent_xml)) {
			// Error condition. Category doesn't have parent.
		} else {
			$$node_xml = $$parent_xml->addChild('item');
			$$node_xml->addAttribute('id', $c['category_id']);
			$$node_xml->addAttribute('name', $c['name']);
		}
	}
}

echo $xml_0->asXML();

One thing I”d like to point out here is that it’s possible that a child category happens before parent category is defined. I currently solve this by just having another iteration for missed categories. One possible improvement on this is to continue looping until $skipped_categories is empty. Be careful when you do loop as it’s highly possible to have infinite loop. If the data happen to be corrupted (e.g. parent node is never defined) you may end up with infinite loop. So to avoid that, have an “upper bound” limit on how many iterations you can do.

There you have it … I hope you enjoyed this article. Please leave comments / suggestions / questions if you have. I’m looking forward to improving my solution with your comments / suggestions / questions.

Pages: 1 2

Leave a Reply

Time limit is exhausted. Please reload the CAPTCHA.