我有一个像这样的数组:
[1] "John", "content1"
[2] "John", "content2"
[3] "John", "content3"
[4] "Jim", "content"
[5] "Joana", "content1"
[6] "Joana", "content2"
我试图得到这样的输出:
<ul>
<li>John
<ul>
<li> content 1 </li>
<li> content 2 </li>
<li> content 3 </li>
</ul>
</li>
<li>Jim
<ul>
<li> content </li>
</ul>
</li>
<li>Joana
<ul>
<li> content 1 </li>
<li> content 2 </li>
</ul>
</li>
</ul>
我尝试使用foreach-iteration解决它,但它根本不起作用: (注意: $ cur_name 表示作者姓名,而 $ content 表示内容)
foreach($array as $a) {
$cur_name = $a['name'];
if ($old_name != $cur_name && $cur_name !="")$return .= "<li>";
if ($old_name != $cur_name && $cur_name !="") {
$return .= "<strong>$cur_name</strong><br />";
}
elseif($cur_name == "") {
}
elseif ($old_name == $cur_name) {
}
$return .= "$content<br />";
if ($old_name != $cur_name && $cur_name !="") $return .= "</li>";
$old_name = $cur_name;
}
}
任何想法都很高兴...
答案 0 :(得分:2)
使用此代码:
做这样的事情:
key
- ed数组(比如说$processedArray
),其中键值取自每个数组的第一个索引$processedArray
以适当地输出它。我知道阅读代码会更容易,所以,试试这个:
<?php
$data = array(
array('name'=>'John', 'content'=>'Content1'),
array('name'=>'John', 'content'=>'Content2'),
array('name'=>'John', 'content'=>'Content3'),
array('name'=>'Jim', 'content'=>'Content'),
array('name'=>'Joana', 'content'=>'Content1'),
array('name'=>'Joana', 'content'=>'Content2'),
);
$processedArray = array();
foreach( $data as $each )
{
if( !isset( $processedArray[ $each[ 'name' ] ] ))
$processedArray[ $each[ 'name' ] ] = array();
$processedArray[ $each[ 'name' ] ][] = $each[ 'content' ];
}
echo "<ul>\n";
foreach( $processedArray as $key => $arrVal)
{
echo " <li>$key\n";
echo " <ul>\n";
foreach( $arrVal as $value )
{
echo " <li>$value</li>\n";
}
echo " </ul>\n";
echo " </li>\n";
}
echo "</ul>\n";
?>
答案 1 :(得分:0)
根据您发布的内容判断,我假设数据如下:
$array = array();
$array[1] = array("name" => "John", "content" => "content1");
$array[2] = array("name" => "John", "content" => "content2");
$array[3] = array("name" =>"John", "content" =>"content3");
$array[4] = array("name" =>"Jim", "content" =>"content");
$array[5] = array("name" =>"Joana", "content" =>"content1");
$array[6] = array("name" =>"Joana", "content" =>"content2");
如果是这种情况,那么您唯一遗漏的是$return .= "$content<br />";
应该看起来像$return.=$a['content']."<br/>"
。此外,您的代码最后有一个额外的大括号,但我认为这只是复制/粘贴。当然,您需要回显$ return变量。
答案 2 :(得分:0)
以下是一些可以为您完成的基本代码:
<ul>
<?php
$array = array(
array( name => 'John',
content => 'content1'),
array( name => 'John',
content => 'content2'),
array( name => 'John',
content => 'content3'),
array( name => 'Jim',
content => 'content'),
array( name => 'Joana',
content => 'content1'),
array( name => 'Joana',
content => 'content2')
);
foreach($array as $a) {
if ($a['name'] != $old_name) {
if (isset($old_name)) $return .= "\t\t</ul>\n\t</li>\n";
$return .= "\t<li><strong>" . $a['name'] . "</strong>\n\t\t<ul>\n";
}
$return .= "\t\t\t<li>" . $a['content'] . "</li>\n";
$old_name = $a['name'];
}
echo "$return\t\t</ul>\n\t</li>\n";
?>
</ul>