2013-04-04 19 views
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++; 
} 

回答

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 />"; 
} 
+0

這種方式比我的方式更簡單更優雅。我一定會在將來這樣做,謝謝! :) – 2013-04-04 15:14:20

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++; 
} 
+0

我不這麼認爲,因爲第二個鍵([X] >> [Y] <<)做不是從每個新組的0開始,請檢查我提供的數組。我嘗試重置y並獲得此通知 – 2013-04-04 15:04:54

+0

注意:未定義的偏移量:0在...上線423 – 2013-04-04 15:05:12

+0

@KelseyThorpe然後使用一段時間不會工作,因爲'count($ groups [$ x] $ y])'on第二個循環將是2,但'y'將等於4 – 2013-04-04 15:07:26

1

您可以嘗試

foreach ($groups as $group) { 
    foreach ($group as $var) { 
     echo $var->searchString, "<br />"; 
    } 
} 
+0

第二個循環不應該在組上?不是羣組 – 2013-04-04 15:07:57

+0

更正了...謝謝 – Baba 2013-04-04 15:09:54

0

嘗試的foreach:

foreach ($groups as $x => $group) 
{ 
    foreach ($group as $y => $subGroup) 
    { 
     echo $subGroup->searchString . '<br>'; 
    } 
    echo '<hr>'; 
}