I'm trying to get all parent id from child id
I have db structure like this
folder db
id parent_id name
1 0 myfolder
2 1 usa
3 2 new york
4 3 people
5 0 myfolder2
now i have folder id as 4 i need to find last parent_id i.e. for id 4 it should return 3,2,1 in one array
to get this result i'm using recursive function
function folder_has_parent($parent,$conobj,$array) {
$return = array();
$selectparent = "select * from pictures_folder where id = $parent ";
$folderResult = mysqli_query($conobj,$selectparent);
$folderRow = mysqli_fetch_assoc($folderResult);
$parent_id = $folderRow['parent_id'];
if ($parent_id != 0) {
array_push($return,$parent_id);
print_r($return);
/*
every time array gets new values i want it should merge into single array and return
Array
(
[0] => 3
)
Array
(
[0] => 2
)
Array
(
[0] => 1
)
*/
$a = folder_has_parent($parent_id, $conobj,$array);
}
return $return;
}
if(isset($folderId)){
$array = array();
$array = folder_has_parent($folderId ,$conobj ,$array);
print_r($array);
// here i m getting return array as
Array
(
[0] => 3
)
}
i m using array_push to store values in array but its getting overiden
You have to use global variable otherwise it will always return array with last value. Because when you do function call it will initialize array and for recursive function call it will behave as same and every time initialize new array.
array_push($GLOBALS['return'],$parent_id);
You can just return true once all process done no need return array as it is global you will get it outside as well. Print $return outside and you will get result which you want.
Its nesned function but you reset the array in every loop, Could you try like this,
function folder_has_parent($parent,$array) {
$selectparent = "select * from pictures_folder where id = $parent ";
$folderResult = mysqli_query($conobj,$selectparent);
$folderRow = mysqli_fetch_assoc($folderResult);
$parent_id = $folderRow['parent_id'];
if ($parent_id != 0) {
$array[] = $parent_id;
folder_has_parent($parent_id,$array);
}
return $array;
}
if(isset($folderId)){
$array = array();
$array = folder_has_parent($folderId ,$array);
print_r($array);
}