我在PHP中有一个数组的以下工作数组:
$explore1 = array
(
array("a.html", "A"),
array("b.html", "B"),
array("c","C")
);
$arrlength = count($explore1);
for($x = 0; $x < $arrlength; $x++) {
echo '<li><a href="'.$explore1[$x][0].'">'.$explore1[$x][1].'</a></li>';
} }
我想从SQL填充explore1数组。如果我只是改变下面的代码它有错误但我不知道我想做什么呢?
$sql = 'SELECT url, name FROM explore_items WHERE menuID="item1"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$explore1 = array //IT DOESN'T LIKE THIS LINE
(
while($row = $result->fetch_assoc()) {
// BUILD SAME LINES AS ABOVE WITH ECHO
echo "array('" . $row["url"]. ", '" . $row["name"]. "'),";
}
);
有人可以帮忙吗?
答案 0 :(得分:1)
你根本不需要$explore1
:
$sql = 'SELECT url, name FROM explore_items WHERE menuID="item1"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
//echo "array('" . $row["url"]. ", '" . $row["name"]. "'),";
echo '<li><a href="'.$row["url"].'">'.$row["name"].'</a></li>';
}
}
或者如果您需要,可以fetch_all()
:
$sql = 'SELECT url, name FROM explore_items WHERE menuID="item1"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$explore1=$result->fetch_all(MYSQLI_ASSOC);
foreach($explore1 as $row ) {
//echo "array('" . $row["url"]. ", '" . $row["name"]. "'),";
echo '<li><a href="'.$row["url"].'">'.$row["name"].'</a></li>';
}
}
答案 1 :(得分:0)
请学习一些php基础知识。 定义数组数组就像:
$explore1 = array();
while($row = $result->fetch_assoc()) {
$explore1[] = array($row["url"], $row["name"]);
}
答案 2 :(得分:0)
您必须在循环内填充数组:
while($row = $result->fetch_assoc()) {
$explore1[$row["url"]] = $row["name"];
}