PHP的Foreach问题?

问题描述:

我试图从$ MySQL数据库中显示$ url值,但我只能得到正确显示$ cat值可以有人请帮助我了解如何显示$ url值。PHP的Foreach问题?

我现在我做错了什么。

这里是部分代码。

// 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 

?> 
+0

您的代码在语法上是正确的。几个问题: 什么是$父数组?你在哪里设置$ url? – jonthornton 2009-11-06 00:34:05

+0

你可能需要发布更多的代码..从你给我们到目前为止,$ url甚至没有定义有一个值.. – saleemshafi 2009-11-06 00:34:41

+0

完整的代码发布。 – aBc 2009-11-06 00:37:50

$ url不在图片中甚至...它看起来像你迭代了一个独立于MySQL结果的数组。你会需要更类似的东西:

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

希望这会有所帮助。

编辑:

首先,$网址需要与您的列表()其他增值经销商一起分配 - 因为你在查询执行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>'; 

} 

从您提供的代码中,您没有从$ parent声明$ url。你有可能提供存储在$ parent中的东西吗?


所以首先要做的第一件事!

您将需要从mysqli_fetch_array调用类似这样的东西(我假设URL是列名在表中)

while ($row = mysqli_fetch_array($dbc, MYSQLI_NUM)) { 
    $id = $row['id']; 
    $parent_id = $row['parent_id']; 
    $cat = $row['category']; 
    $url = $row['url']; 

    // Add to the array: 
    $link[$parent_id][$id] = array('cat' => $cat, 'url' => $url); 
} 

获取URL然后改变你的foreach循环来提取相应的类别, url

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

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