Я прохожу через некоторые местоположения, а затем вызываю рекурсивную функцию, чтобы получить эти категории категорий и подкатегорий. Что происходит, когда функция возвращает данные в виде комбинации предыдущего результата цикла. Как я могу избавиться от этого, пожалуйста, помогите мне в этом, мой код выглядит так.PHP-рекурсивная функция внутри цикла foreach сбрасывает предыдущие данные в следующем цикле
foreach ($data as $row) {
$get_options = categoryWithSubcategories(0, 0,$row['location_id'],$dbConn);
// here I am passing $row['location_id'] to this function, but it merge prvious data within next loop.
}
Рекурсивная функция ниже.
function categoryWithSubcategories($current_cat_id, $count,$locationId,$dbConn)
{
static $option_results;
// if there is no current category id set, start off at the top level (zero)
if (!isset($current_cat_id)) {
$current_cat_id =0;
}
// increment the counter by 1
$count = $count+1;
// query the database for the sub-categories of whatever the parent category is
$sql = "SELECT cat_id, cat_name from tbl_category where cat_parent_id = $current_cat_id and locationid=$locationId and delete_flag='0'";
$stmt = $dbConn->prepare($sql);
$result =$stmt->execute();
$data = $stmt->fetchAll();
$num_options = $stmt->rowCount();
if ($num_options > 0) {
foreach ($data as $categoryList) {
// if its not a top-level category, indent it to
//show that its a child category
if ($current_cat_id!=0) {
$indent_flag = ' ';
for ($x=2; $x<=$count; $x++) {
$indent_flag .= ' >> ';
}
}
$cat_name = $indent_flag.$categoryList['cat_name'];
$option_results[$categoryList['cat_id']] = $cat_name;
// now call the function again, to recurse through the child categories
categoryWithSubcategories($categoryList['cat_id'], $count,$locationId,$dbConn);
}
}
return $option_results;
}
вы думали об изменении SQL, чтобы восстановить всю информацию вам нужно? – atoms
Вам не хватает заявления о возврате? 'return categoryWithSubcategories ($ categoryList ['cat_id'], $ count, $ locationId, $ dbConn);' внутри цикла foreach – Sepultura