2012-05-17 50 views
1

即時嘗試在我的foreach循環中反轉結果,我知道我可以嘗試使用array_reverse,但不會反轉循環的輸出。反向foreach結果

結果目前這個樣子

[new Date(2012, 05, 16), 630.10, 615.94], 
[new Date(2012, 05, 15), 615.00, 603.75], 
[new Date(2012, 05, 14), 608.50, 600.58], 
[new Date(2012, 05, 11), 614.55, 604.77], 
[new Date(2012, 05, 10), 616.19, 610.23], 

我想輸出是

[new Date(2012, 05, 10), 616.19, 610.23], 
[new Date(2012, 05, 11), 614.55, 604.77], 
[new Date(2012, 05, 14), 608.50, 600.58], 
[new Date(2012, 05, 15), 615.00, 603.75], 
[new Date(2012, 05, 16), 630.10, 615.94], 

這是我的代碼。

foreach($stockcontentex as $stockexplode){ 
    $stockex = explode(',',$stockcontentex[$i++]); 
    $stockexdate = explode('-', $stockex[0]); 
    $stockYear = $stockexdate[0]; 
    $stockMonth = $stockexdate[1]; 
    $stockDay = $stockexdate[2]; 
    $stockHigh = $stockex[2]; 
    $stockLow = $stockex[3]; 
    $_str .= '[new Date('.$stockYear.', '.$stockMonth.', '.$stockDay.'), '.$stockHigh.', '.$stockLow.'],'. "\n"; 

    } 

任何幫助表示讚賞,我不知道是否有任何其他信息可能需要。

感謝

+0

你想要什麼輸出? – xbonez

+0

看看更新的代碼 – user874185

+1

'$ i'是什麼?我覺得你對''foreach'''' – knittl

回答

1

使用array_reverse然後交換這樣的:

$stockex = explode(',',$stockcontentex[$i++]); 

與此:

$stockex = explode(',',$stockexplode); 

另外,還可以切換爲.=

$_str = '[new Date('.$stockYear.', '.$stockMonth. 
      ', '.$stockDay.'), '.$stockHigh.', '.$stockLow.'],'. "\n" . $_str; 
+0

這個代碼更感興趣,但是循環給了我這個問題。這不是所有的代碼,但只是一個想法,我在做什麼http://pastebin.com/iwbbBwt2 – user874185

+0

我喜歡你的替代方案,但它不斷顯示循環之外的結果,而不是內部,這就是我所做的http: //pastebin.com/sPa1jWJm – user874185

0

雖然我個人用@ cwallenpoole的答案走,一個替代方案是:

$stockcount = count($stockcontentex); 
for ($i = $stockcount; $i >= 0; $i--) { 
    $stockex = explode(',',$stockcontentex[$i++]); 
    $stockexdate = explode('-', $stockex[0]); 
    $stockYear = $stockexdate[0]; 
    $stockMonth = $stockexdate[1]; 
    $stockDay = $stockexdate[2]; 
    $stockHigh = $stockex[2]; 
    $stockLow = $stockex[3]; 
    $_str .= '[new Date('.$stockYear.', '.$stockMonth.', '.$stockDay.'), '.$stockHigh.', '.$stockLow.'],'. "\n"; 
} 
0

我創造了這個辦法扭轉循環遍歷一個數組:
(在這種情況下,模擬反向的foreach)

if(!empty($array)) { 
    $value = end($array); 
    $key = key($array); 
    do { 

     /** 
     * Do your stuff here 
     * Could be old code/stuff here that worked with foreach($array as $key => $value) 
     */ 

     $value = prev($array); 
     $key = key($array); 
    } while($key !== null); 
} 

注:這是一個黑客攻擊的一位。但它應該適用於你想要反向遍歷的每種(關聯)數組。