gpt4 book ai didi

PHP Foreach 问题?

转载 作者:太空宇宙 更新时间:2023-11-03 11:20:02 26 4
gpt4 key购买 nike

我正在尝试从 MySQL 数据库中获取要显示的 $url 值,但我只能获取要正确显示的 $cat 值,有人可以帮助我学习如何显示 $url 值。

我现在做错了。

这是部分代码。

// Loop through each subarray:
foreach ($parent as $id => $cat) {

// Display the item:
echo '<li><a href="http:' . $url . '" title="">' . $cat . '</a>';

这是完整的代码。

<?php
require_once ('./mysqli_connect.php'); // Connect to the db.

// Receives one argument: an array.
function make_list ($parent) {

// Need the main $link array:
global $link;

// Start an ordered list:
echo '<ol>';

// Loop through each subarray:
foreach ($parent as $id => $cat) {

// Display the item:
echo '<li><a href="http://' . $url . '" title="">' . $cat . '</a>';

// Check for sublink:
if (isset($link[$id])) {

// Call this function:
make_list($link[$id]);

}

// Complete the list item:
echo '</li>';

} // End of FOREACH loop.

// Close the ordered list:
echo '</ol>';

} // End of make_list() function.


// Connect to the database:
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT * FROM categories ORDER BY parent_id, category ASC");
if (!$dbc) {
// There was an error...do something about it here...
print mysqli_error();
}


// Initialize the storage array:
$link = array();

while (list($id, $parent_id, $category) = mysqli_fetch_array($dbc, MYSQLI_NUM)) {

// Add to the array:
$link[$parent_id][$id] = $category;

}

make_list($link[0]);


mysqli_close($mysqli); // close the connection

?>

最佳答案

$url 甚至不在图片中...看起来您正在迭代一个与 MySQL 结果分开的数组。您将需要更多类似的东西:

foreach ($res as $row) {
echo '<li><a href="http:' . $row['url'] . '" title="">' . $row['cat'] . '</a>';
}

希望这对您有所帮助。

编辑:

首先,$url 需要与 list() 中的其他变量一起分配 - 因为您在查询中执行 SELECT *,您可能需要指定列,以便分配中的顺序正确。

那么,就没有办法在您正在使用的数组结构中包含另一个变量...

$link[$parent_id][$id] =  $category;

必须是这样的:

$link[$parent_id][$id] =  array('category' => $category, 'url' => $url);

然后,遍历数组需要更改为:

foreach ($parent as $id => $ary) {

// Display the item:
echo '<li><a href="http:' . $ary['url'] . '" title="">' . $ary['category'] . '</a>';

}

关于PHP Foreach 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1684625/

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