1

我试图在我的 foreach 循环中反转结果,我知道我可以尝试使用 array_reverse 但这不会反转循环的输出。

结果目前看起来像这样

[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";

    }

任何帮助表示赞赏,我不确定是否需要任何其他信息。

谢谢

4

3 回答 3

1

使用array_reverse然后交换这个:

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

有了这个:

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

或者,您可以切换.=为:

 $_str = '[new Date('.$stockYear.', '.$stockMonth.
           ', '.$stockDay.'), '.$stockHigh.', '.$stockLow.'],'. "\n" . $_str;
于 2012-05-17T14:49:20.023 回答
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";
}
于 2012-05-17T14:56:24.557 回答
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);
}

注意:这有点骇人听闻。但它应该适用于您想要反向遍历的每种(关联)数组。

于 2014-11-20T14:06:23.003 回答