Hello. I am doing a small student project and I have a difficulty that I cannot resolve without outside help. In the project I need to add products to the dish from which this dish consists and on the page should be calculated the nutritional value of the dish, depending on the type of processing (For example, raw potatoes (conditionally) nutritional value: 0.6, type of processing: cook, factor for boiled potatoes 2 , then 0.6 * 2 = 1.2, then add the next product, etc.). With this I have no difficulties, the difficulty is that the dish may consist of other dishes and then it turns out the structure of the form "tree", which can be any nesting. I pull the data out of the database by recursive function and, for example, first boiled the potatoes, then fried, and then baked (conditionally), i.e. The dish consists of 3 sub-dishes and each has its own processing coefficient. Assume the nutritional value of raw potatoes 1, the coefficient for cooking potatoes 2, for frying 3, for baking 4. Ie First, we cook: 1 * 2 = 2, then fry boiled potatoes: 2 * 3 = 6, then we bake fried (previously boiled) potatoes: 6 * 4 = 24;
I can't multiply all the nestings, I get that each nesting is multiplied only by the processing coefficient of its level, but not multiplied by the coefficient that is higher in the hierarchy.
Here is my wrong function:
function tree($id_blud, $level) { static $arr = array(); // статическая переменная в которой накапливается пищевая ценность static $ko = array(); // статическая переменная в которой сохраняются коэффициенты обработки вложенных блюд $data = $this->getmysqldata('tree', $id_blud); // данные о продуктах в выбранном блюде $max = count($data); // количество продуктов в блюде for ($i = 0; $i < $max; $i++) { // проходим каждый продукт в блюде $data_recalc = $this->getmysqldata('recalculation', $id_blud, $data[$i]['id_prod'], $data[$i]['id_obrab']); // пищевая ценность i-го продукта echo "<div style='margin-left: " . ($level * 25) . "px;'>" . $data[$i]['nazv_prod'] . "</div>"; if ($level == 0) // если вложенности нет for ($j = 0; $j < 13; $j++) $arr[$j] += $data_recalc[$j]['recalc']; // складываем пищевую ценность для каждого пищевого элемента (всего их 13: белки, жиры, углеводы, натрий, калий и т.д.) в статическую переменную $arr if ($level > 0 and $data[$i]['vid'] == 0) // если больше одного уровня вложенности, т.е. если блюдо в блюде, и это продукт, а не блюдо for ($j = 0; $j < 13; $j++) $arr[$j] += ($data_recalc[$j]['recalc'] * $ko[$level][$j]['ko_blud']); // складываем пищевую ценность для каждого пищевого элемента умноженного на коэффициент обработки вложенного блюда if ($data[$i]['vid'] == 1) { // если данный продукт является блюдом, то рекурсивно вызываем данную функцию и получаем коэффициенты обработки данного вложенного блюда $level++; // уровень вложенности $ko[$level] = $this->getmysqldata('tree2', $data[$i]['id_obrab']); // получаем коэффициенты обработки вложенного блюда для каждого пищевого элемента $this->tree($data[$i]['id_prod'], $level); // рекурсивно вызываем данную функцию $level--; // уровень вложенности } } return $arr; // возвращаем пищевую ценность всего блюда }