2011-06-12 137 views
1

說我創建一個遞歸陣列與此代碼:如何從遞歸數組內的數組中獲取數據?

$digits = 0; 
$tens = 0; 
$hundreds = 0; 

for($i = 0; $i <= 100; $i++) 
{ 
    $myArray[$hundreds][$tens][$digits] = $i; 

    $digits++; 
    if($digits > 9) 
    { 
     $digits = 0; 
     $tens++; 
    } 

    if($tens > 9) 
    { 
     $tens = 0; 
     $hundreds++; 
    } 
} 

我怎麼可能回聲出fromt的'tens array' == 2所有的數據?

要清楚,我會尋找這些結果:

20 21 22 23 24 25 26 27 28 29 

因爲使用基地10 IM,我可能只是這樣做:

for($i=0; $i < 10; $i++) 
{ 
    echo $myArray[0][2][$i] 
} 

但如果我不知道數字數組中有多少個元素?

回答

2
foreach($myArray[0][2] as $v) { 
echo $v."<br>\n"; 
} 
+0

好的謝謝!我知道這一定很簡單。 – SlickRick 2011-06-12 10:51:57

+1

用PHP一切都很簡單(幾乎) – dynamic 2011-06-12 10:59:50

0
<?php 
$tensArr = $myArray[0][2]; 
for($i= 0 ; $i < count($tensArr); $i++) 
{ 
    echo $tensArr[$i]."\n" ; 

} 
+0

爲了防止在每個循環中運行count(),可以設置一個初始變量:'for($ i = 0,$ count = count($ tensArr); $ i <$ count; $ i ++)' – hakre 2011-06-12 11:07:24

+0

@hakre,它有什麼不同?它似乎甚至沒有微觀優化或糾正代碼?請分享您的觀點。 – DhruvPathak 2011-06-12 11:09:29

+0

@hakre,這並沒有什麼幫助。計數函數是0(1),在這裏看到更多... http://stackoverflow.com/questions/4566314/php-what-is-the-complexity-ie-o1-on-of-the-function-count – DhruvPathak 2011-06-12 11:20:33