ul和li与php数组

时间:2013-01-14 04:13:02

标签: php arrays html-lists

如何将正确的ul和li标签添加到以下数组中?请记住一些机会和活动没有价值......我认为需要if语句,但不确定是否只需在每个数组中需要推送或添加ul和li标签:

<?php 
include('common_functions.php');
include('config.php');

?>

<?php
$data = array();
$index = array();
$query = mysql_query("SELECT Opportunity_ID AS id, Parent_ID AS parent_id, Subject AS name FROM Opportunities ORDER BY name");
while ($row = mysql_fetch_assoc($query)) {
    $id = $row["id"];
    $parent_id = $row["parent_id"] === NULL ? "NULL" : $row["parent_id"];
    $data[$id] = $row;
    $index[$parent_id][] = $id;
}
foreach($data as $id)
{
$in_clause .= "'".$id["id"]."',"; }
$in_clause = trim($in_clause, ",");

$activities = array();
$act_query = mysql_query("SELECT Details, Opportunity_ID FROM Activities WHERE Opportunity_ID IN ($in_clause)");
while ($act_row = mysql_fetch_assoc($act_query)) {
    $activities[] = $act_row;
} 


function display_child_nodes($parent_id)
{
    global $data, $index, $activities;
    $parent_id = $parent_id === NULL ? "0" : $parent_id;
    if (isset($index[$parent_id])) 
    {
        foreach ($index[$parent_id] as $id) 
        {
            echo $data[$id]["name"];
            foreach ($activities as $activity)
            {
            if ($activity['Opportunity_ID'] == $id)
            {
            echo $activity['Details'];
            }
            }
            display_child_nodes($id);
         }     
    }    
}

display_child_nodes(NULL, 0);

?>

1 个答案:

答案 0 :(得分:1)

您的代码非常难以理解,“正确”有点含糊不清,因为有很多不同的方法可以做到这一点。

在说 - 你可以implode它。 Implode是一种用胶水缝合阵列的非常简单和整洁的方法。

拿一个二维阵列:

$array[0]= array("one", "two", "three");
$array[1]= array("four", "five", "six");

并循环播放

$output = "";


foreach($array as $item){
    $output .= "<ul><li>".implode("</li><li>",$item)."</li><\ul>";
}

echo $output;

看一下php.net网站上的例子,它充满了很棒的想法:)