我的功能有问题。
我创建了一个函数,该函数可以读取DB中的表并从一列中找到DISTINCT值。
第一个循环是循环遍历DISTINCT值 第二个循环是从另一列获取值。
当我从第二个循环中收集数据时,一切似乎都很好,但是当我尝试在循环外回显变量时,该值已更改为我不知道其来源。
我对PHP相当陌生,无法在任何地方找到解决方案。
功能:
function region_tilbehor() {
include '../db.php';
global $fdato;
global $tdato;
$query_tilbehor = "SELECT DISTINCT region FROM salg";
$result_tilbehor = mysqli_query($connect, $query_tilbehor);
while($row_tilbehor = mysqli_fetch_array($result_tilbehor)) {
$region = $row_tilbehor['region'];
$sql_tilbehor = "SELECT * FROM salg WHERE region='$region' AND kategori LIKE 'tilbehor' AND dato BETWEEN '$fdato' AND '$tdato'";
$kjor_tilbehor = mysqli_query($connect, $sql_tilbehor);
$qty = 0;
while ($num = mysqli_fetch_array($kjor_tilbehor)) {
$sum = $num['belop'];
$qty += $sum;
}
$qty .= ", ";
echo $qty; //gives this: 54726, 14313, 23689, 5885, 39783,
//This is the value i want to return from function.
}
echo "same variable outside loop: " .$qty; //Gives this: same variable outside loop: 39783,
return $qty;
}
答案 0 :(得分:0)
function region_tilbehor() {
include '../db.php';
global $fdato;
global $tdato;
$sumArray = [];
$query_tilbehor = "SELECT DISTINCT region FROM salg";
$result_tilbehor = mysqli_query($connect, $query_tilbehor);
while($row_tilbehor = mysqli_fetch_array($result_tilbehor)) {
$region = $row_tilbehor['region'];
$sql_tilbehor = "SELECT * FROM salg WHERE region='$region' AND kategori LIKE 'tilbehor' AND dato BETWEEN '$fdato' AND '$tdato'";
$kjor_tilbehor = mysqli_query($connect, $sql_tilbehor);
$qty = 0;
while ($num = mysqli_fetch_array($kjor_tilbehor)) {
$sum = $num['belop'];
$qty += $sum;
}
$qty .= ", ";
array_push($sumArray,$qty);
echo $qty; //gives this: 54726, 14313, 23689, 5885, 39783,
//This is the value i want to return from function.
}
print_R($sumArray);die; //Gives this: same variable outside loop: 39783,
return $qty;
}