多维数组Foreach - 显示在不同的表中

时间:2011-09-27 23:35:00

标签: php multidimensional-array

我目前有以下数组:

Array
(
    [group] => Array
        {
            [5] => group1-title
            [6] => group2-title
        }
    [treatment] => Array
        (
            [5] => Array
                (
                    [16] => Array
                        (
                            [title] => title1
                            [description] => description1
                            [price] => price1
                        )

                    [17] => Array
                        (
                            [title] => title2
                            [description] => description2
                            [price] => price2
                        )
            [6] => Array
                (

                    [21] => Array
                        (
                            [title] => title3
                            [description] => description3
                            [price] => price3
                        )
                }
        }
}

(实际上,数组数据很大,所以它已被裁剪以提供上面的例子)

我尝试做的是在数组上运行foreach循环,以便我可以将定价表中的数据按其组分组(数组键[5][6]

我的目标最终结果如下:

组别1-标题


标题1 |描述|价格
标题2 |描述|价


组2-标题


标题3 |描述|价


到目前为止,我已尝试使用带有内部foreach循环的foreach循环。这将细节和回声拉得很好 - 但我无法弄清楚如何在foreach循环期间成功分组数据。

2 个答案:

答案 0 :(得分:3)

这是一种解决方法。抓取第一个数组项并将其用于标题。然后使用第一项中的键循环遍历数组的其余部分以显示结果。显然我的显示代码很快且很脏,但这应该可以让你开始。

foreach($your_array['group'] as $iGroupId => $sTitle) {
    echo 'Group: ' . $sTitle . "\n";
    foreach($your_array['treatment'][$iGroupId] as $aGroup) {
        echo implode('|', $aGroup); . "\n"
    }
}

答案 1 :(得分:3)

$data = array(); //your data array above

//loop through the groups    
foreach($data['group'] as $key=>$group){
    //echo group header and table start
    echo "<h1>$group</h1>";
    echo "<table border=1>";
    //loop through the data with the corresponding group key
    foreach($data['treatment'][$key] as $row){
        //echo row data
        echo "<tr>";
        echo "<td>{$row['title']}</td>";
        echo "<td>{$row['description']}</td>";
        echo "<td>{$row['price']}</td>";
        echo "</tr>";
    }
    //close table.
    echo "</table>";
}