请比较下面的CURRENT
和DESIRED
结果,看看我想做什么。
$arr=array(
array('list_name'=>'Food', 'list_item'=>'bread'),
array('list_name'=>'Food', 'list_item'=>'meat'),
array('list_name'=>'Drinks', 'list_item'=>'water'),
array('list_name'=>'Drinks', 'list_item'=>'milk')
);
foreach($arr as $row){
echo $row['list_name'].'<br>';
echo $row['list_item'].'<br>';
echo '<br>___<br>';
}
当前结果Food
bread
___
Food
meat
___
Drinks
water
___
Drinks
milk
___
想要的结果
Food
1.bread
2.meat
___
Drinks
1.water
2.milk
___
更复杂,但更一般化的例子:
$arr=array(
array('list_name'=>'Food', 'list_item1'=>'bread', 'list_item2' => 2001),
array('list_name'=>'Food', 'list_item1'=>'meat', 'list_item2' => 2002),
array('list_name'=>'Drinks', 'list_item1'=>'water', 'list_item2' => 2003),
array('list_name'=>'Drinks', 'list_item1'=>'milk', 'list_item2' => 2004)
);
想要的结果
Food
1.bread, 2001
2.meat, 2002
___
Drinks
1.water, 2003
2.milk, 2004
___
您可以遍历数组并将项目数据添加到新数组中(每个list_name
一个)。
$new_array = array();
foreach ($arr as $row)
{
$new_array[$row['list_name']][] = $row['list_item'];
}
foreach ($new_array as $name => $items)
{
echo $name . '<br>';
foreach ($items as $index => $item)
{
echo ($index + 1) . '. ' . $item . '<br>';
}
echo '___<br>';
}
与您的更新:
$new_array = array();
foreach ($arr as $row)
{
$name = $row['list_name'];
unset($row['list_name']);
$new_array[$name][] = $row;
}
foreach ($new_array as $name => $items)
{
echo $name . '<br>';
foreach ($items as $index => $item)
{
echo ($index + 1) . '. ' . implode(', ', $item) . '<br>';
}
echo '___<br>';
}
$arr=array(
array('list_name'=>'Food', 'list_item'=>'bread'),
array('list_name'=>'Food', 'list_item'=>'meat'),
array('list_name'=>'Drinks', 'list_item'=>'water'),
array('list_name'=>'Drinks', 'list_item'=>'milk')
);
$names = array();
foreach ( $arr as $item){
$name = $item['list_name'];
if(!in_array($name, $names)){
$names[] = $name;
echo $name ."<BR>";
}
echo $item['list_item']."<BR>";
}
一个常见的方法是在遍历列表时将当前标题/节存储到一个变量中。然后,每次遇到新标题时,您都要回叫该标题,并重新开始编号(或关闭HTML <ol>
标记等)。
$current_section = NULL;
foreach ( $arr as $row )
{
if ( $current_section != $row['list_name'] )
{
// Begin new section
echo $row['list_name'];
// Remember current section
$current_section != $row['list_name'];
}
// Output current item
echo $row['list_item'];
}
注意,这种方法将只有工作,如果你的列表排序,使所有的"食物"项目在一起,然后是所有的"饮料",等等。
否则,您可以使用另一种方法来重新构造数组,以便每个部分都有一个子数组,然后使用一对嵌套循环:
$new_array = array();
foreach ($arr as $row)
{
$new_array[$row['list_name']][] = $row['list_item'];
}
foreach ( $new_array as $section_name => $items )
{
echo $section_name;
foreach ( $items as $row )
{
echo $row;
}
}
好的,我之前犯了一个错误,但我测试了这个,它确实工作。
<?php
$food = array('bread', 'meat');
$drink = array('water', 'milk');
$object = array('food' => $food, 'drink' => $drink);
foreach($object as $row){
echo $row[0].'<br>';
echo $row[1].'<br>';
echo '<br>___<br>';
}
?>