I have a table that have 3 columns. id, parent_id and text
. I want a function that returns all parent id
of an id
..
Suppose that I pass a parameter 4
which is the ID
, the array should return 4,3,2,1
because 3 is the parent of 4, 2 is the parent of 3 and similarly, 1 is the parent of 2. How can I achieve that?
I have tried this so far. But this is returning arrays..
function getTree($id){
$arr = array();
$parent = mysql_query("SELECT parent_id FROM task WHERE id = '".$id."'");
$parent_query = mysql_fetch_assoc($parent);
if ($parent_query['parent_id']==0){
echo "This is the parent";
} else {
$arr[] = $id;
$arr[] = $parent_query['parent_id'];
$arr[] = getTopTree($parent_query['parent_id']);
echo '<pre>';
print_r($arr);
echo '</pre>';
}
}
You can create a custom function of your own like as
function checkParentIds($id, $data = array()) {
$parent = mysql_query("SELECT parent_id FROM task WHERE id = '$id'");
$parent_query = mysql_fetch_assoc($parent);
if ($parent_query['parent_id'] > 0) {
$data[] = $parent_query['parent_id'];
checkParentIds($parent_query['parent_id'], $data);
} else {
$parent_result = (empty($data)) ? 1 : implode("','", $data);
}
return $parent_result;
}
select id, group_concat(parent_id) as parents, test <yourtable> group by id;
and then in php you can just explode an appropriate column of retrieved row:
// ... retrieving all the rows stuff
$parentsIds = explode(',', $row['parents']);