Alphy Alphy - 3 months ago 25
PHP Question

Codeigniter Equivalent

I am looking for a slight help, much appreciated, I have a raw spaghetti php code I am converting to codeigniter, seems to work but output not exact, What is my syntax missing

raw php

function displayMenu($parent =0) {

$query =mysql_query("SELECT * "
. " FROM tbl_org_structure "
. "WHERE parent_id='$parent'"

) or die(mysql_error());
if(mysql_num_rows($query) > 0 ){
echo '<ul>';
while ($row = mysql_fetch_array($query)) {
echo '<li>'.$row['name'];
displayMenu($row['id']);
echo '</li>';
}
echo '</ul>';
}
}


my codeigniter equivalent

function getHierarchy($parent=0){

$hierarchy = $this->db
->where('parent_id',$parent)
->get('tbl_org_structure')
->result();
$stringBuilder='<ul>';
foreach ($hierarchy as $chainOfCommand):
$stringBuilder.='<li>'.$chainOfCommand->name;
$this->getHierarchy($chainOfCommand->id);
$stringBuilder.='</li>';
endforeach;
$stringBuilder.='</ul>';

echo $stringBuilder;

}


raw php output

Board of Directors

Chief Executive Officer (CEO)
Finance Department
FC
test
CA
Human Resources Department (HR)
HOR
MO
IT Department
TSM
Sys Dev
Sales Department
Acc M
MD
Production
PC
DM


codeigniter output

test

FC
CA

HOR
MO

TSM
Sys Dev

Acc M
MD

PC
DM

Finance Department
Human Resources Department (HR)
IT Department
Sales Department
Production

Chief Executive Officer (CEO)

Board of Directors


suggestions

Answer

You're echoing the results before coming back up the recursion stack, so you're travelling all the way down to a leaf in your heirarchy, echoing that leaf, coming back and echoing the parent, and so on. You should return $stringBuilder instead. Then you'd need the calling code to echo getHierarchy().

Or, just echo everything immediately like is being done in displayMenu, instead of building a string.