我正在尝试从多维数组输出分组数据。考虑最高级别的数组键“组”,然后在组内是各个搜索行。
e.g。 $group[ 0 ][ 1 ]
将是“第1组,第1行”。
我想显示每个组中的所有行,然后通过插入“<hr />
”标记来表示该组已更改。在第一组正确显示的时刻,然后显示hr标签,但不显示第二组结果。我的循环循环方法是错误的吗?可以像这样使用多维数组吗?
谢谢!
我的数组看起来像这样:
Array
(
[0] => Array
(
[0] => stdClass Object
(
[name] => testing
[searchID] => 131
[lineID] => 190
[searchString] => 1
)
[1] => stdClass Object
(
[name] => testing
[searchID] => 131
[lineID] => 191
[searchString] => 2
)
[2] => stdClass Object
(
[name] => testing
[searchID] => 131
[lineID] => 192
[searchString] => 3
)
[3] => stdClass Object
(
[name] => testing
[searchID] => 131
[lineID] => 193
[searchString] => 4
)
)
[1] => Array
(
[4] => stdClass Object
(
[name] => test2
[searchID] => 132
[lineID] => 199
[searchString] => 1
)
[5] => stdClass Object
(
[name] => test2
[searchID] => 132
[lineID] => 200
[searchString] => 2
)
)
)
我的代码如下所示:
$x = 0;
$y = 0;
while( $x < count( $groups ) )
{
while( $y < count( $groups[ $x ] ) )
{
//display each single search string
echo $groups[ $x ][ $y ]->searchString.'<br>';
$y++;
}
echo '<hr>';
$x++;
}
答案 0 :(得分:1)
你可以尝试
foreach ( $groups as $group ) {
foreach ( $group as $var ) {
echo $var->searchString, "<br />";
}
}
答案 1 :(得分:0)
您需要在第一个循环内重置y
。
$x = 0;
while( $x < count( $groups ) )
{
$y = 0;
while( $y < count( $groups[ $x ] ) )
{
//display each single search string
echo $groups[ $x ][ $y ]->searchString.'<br>';
$y++;
}
echo '<hr>';
$x++;
}
答案 2 :(得分:0)
查看示例数组,第二组的y值应该从4开始并循环直到达到6。
我建议你使用foreach循环。 http://php.net/manual/en/control-structures.foreach.php
您的代码如下所示:
foreach ( $groups as $gKey => $gValue )
{
foreach ( $gValue as $key => $value )
{
echo $groups[$gKey][$key]->searchString . "<br />";
// or $value->searchString . "<br />";
}
echo "<hr />";
}
答案 3 :(得分:0)
尝试foreach:
foreach ($groups as $x => $group )
{
foreach ($group as $y => $subGroup )
{
echo $subGroup->searchString . '<br>';
}
echo '<hr>';
}