0

我正在尝试从多维数组中输出分组数据。考虑最高级别的数组键“组”,然后在组内是单独的搜索行。

例如$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++;
 }
4

4 回答 4

1

你可以试试

foreach ( $groups as $group ) {
    foreach ( $group as $var ) {
        echo $var->searchString, "<br />";
    }
}
于 2013-04-04T15:06:11.497 回答
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++;
}
于 2013-04-04T15:02:25.450 回答
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 />";
}
于 2013-04-04T15:06:53.567 回答
0

尝试foreach:

foreach ($groups as $x => $group )
{
    foreach ($group as $y => $subGroup )
    {
        echo $subGroup->searchString . '<br>';
    }
    echo '<hr>';
}
于 2013-04-04T15:07:41.500 回答