execute(-6ren">
gpt4 book ai didi

php - 为什么 while 循环运行一次?

转载 作者:行者123 更新时间:2023-11-29 05:57:19 25 4
gpt4 key购买 nike

下面的代码只运行一次,而它应该运行的次数是 4,有帮助吗?

PHP::

<?php

header("Content-Type: application/json");

require_once("config.php");

if(isset($_GET["m"])) {

$dirname = "images/main/";
$arr = array();

$conn = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);

if(!$conn) {
echo "Error connecting to database";
exit();
}
if($stmt = $conn->prepare("SELECT name_ FROM projects")) {
$stmt->execute();
$stmt->bind_result($n);
//$stmt->store_result();
$result = $stmt->get_result();
if($result->num_rows == 0) {
echo "No Projects";
$stmt->close();
$conn->close();
exit();
}else {
while ($row = $result->fetch_assoc()) {
$dirname = $dirname . $row["name_"] . "/";
$images = glob($dirname . "*.*", GLOB_BRACE);
foreach($images as $image) {
echo $row["name_"];
echo$result->num_rows; // returns 4 !!!!
$image = base64_encode($image);
//$arr[] = $image;
array_push($arr, $image);
$image = "";
}
}
echo json_encode($arr); // returns 1 json row oonly
}
}

$stmt->close();
$conn->close();
exit();

}

?>

num rows 返回 4 那么为什么它只运行或循环一次?

我正在尝试从图像文件夹中获取图像以回显它

修复::

根据 jhilgeman 的回答,我将这部分添加到 foreach 的末尾:

$dirname = "images/main/";

最佳答案

如果非要我猜的话,我会说它循环正确,但问题出在这一行:

$dirname = $dirname . $row["name_"] . "/";

每次循环时,您都将 $row["name"] 值附加到 $dirname 是什么。假设您像这样返回 4 行:

name
----
houses
boats
computers
animals

在循环的开始,假设 $dirname 只是“/images/”。所以第一个循环会将 $dirname 更改为:

/images/houses/

然后第二个循环会把它改成:

/images/houses/boats/

然后第三个循环会成功:

/images/houses/boats/computers/

最后是第四个循环:

/images/houses/boats/computers/animals/

因此,除非您期望 $dirname 以这种方式附加,否则您可能想要替换 $dirname 而不是每次都附加到它。

为你的循环试试这个:

while ($row = $result->fetch_assoc()) {
$images_dirname = $dirname . $row["name_"] . "/";
$images = glob($images_dirname . "*.*", GLOB_BRACE);

foreach($images as $image) {
...etc...
}
}

关于php - 为什么 while 循环运行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48234284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com