我试图从多维数组输出分组数据。考虑最高级数组键'group',然后在组中是单独的搜索行。
。$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++;
}
你可以试试
foreach ( $groups as $group ) {
foreach ( $group as $var ) {
echo $var->searchString, "<br />";
}
}
看一下你的示例数组,第二组的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 />";
}
您需要在第一个循环内重置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++;
}
Try foreach:
foreach ($groups as $x => $group )
{
foreach ($group as $y => $subGroup )
{
echo $subGroup->searchString . '<br>';
}
echo '<hr>';
}