PHP / Laravel,foraeach :( $ array as $ value)工作,($ array as $ key => $ value)不行?!

时间:2016-11-17 19:07:20

标签: php arrays laravel-5

我不知道如何以另一种方式解释我的问题,而不是举一个例子。希望这没关系。

我定义了两个数组:

$range = ['1000' => '1100', '1100' => '1200', '1200' => '1300'];

$years = ['2010', '2011'];

然后我尝试从给定的数据库中获取数据,如:

        foreach ($years as $year) {
        foreach ($range as $from => $to) {
            $result[$year][$from] = Flight::leftJoin('aircrafts', 'flights.LFZ_LFDNR', '=', 'aircrafts.LFZ_LFDNR')
                ->selectRaw('aircrafts.GEWICHT, SUM(flights.ANZLDG) AS LANDUNGEN')
                ->whereYear('DATUM', '==', $year)
                ->where('GEWICHT', '>=', $from)
                ->where('GEWICHT', '<', $to)
                ->count();
        };
    };

与输出完美配合,如:

{

"2010": {
    "1000": 821,
    "1100": 979,
    "1200": 126,
    "1300": 127,
    "1400": 69,
    "1500": 157,
    "1600": 33,
    "1700": 364,
    "1800": 64,
    "1900": 69
},
"2011": {
    "1000": 891,
    "1100": 1027,
    "1200": 112,
    "1300": 128,
    "1400": 76,
    "1500": 135,
    "1600": 64,
    "1700": 701,
    "1800": 96,
    "1900": 67
}

}

我将$ years数组更改为:

$years = ['2010'=>'red','2011'=>'green'];

和查询:

        foreach ($years as $year => $color) {
        foreach ($range as $from => $to) {
            $result[$year][$from] = Flight::leftJoin('aircrafts', 'flights.LFZ_LFDNR', '=', 'aircrafts.LFZ_LFDNR')
                ->selectRaw('aircrafts.GEWICHT, SUM(flights.ANZLDG) AS LANDUNGEN')
                ->whereYear('DATUM', '==', $year)
                ->where('GEWICHT', '>=', $from)
                ->where('GEWICHT', '<', $to)
                ->count();
        };
    };

我得到了什么:

{

"2010": {
    "1000": 0,
    "1100": 0,
    "1200": 0,
    "1300": 0,
    "1400": 0,
    "1500": 0,
    "1600": 0,
    "1700": 0,
    "1800": 0,
    "1900": 0
},
"2011": {
    "1000": 0,
    "1100": 0,
    "1200": 0,
    "1300": 0,
    "1400": 0,
    "1500": 0,
    "1600": 0,
    "1700": 0,
    "1800": 0,
    "1900": 0
}

}

我不知道为什么我会得到&#34; 0&#34;!当我尝试调试并检查$ year var时,它仍然具有正确的值。如果我插入例如&#39; 2010&#39;在 - &gt; whereyear()中代替$ year,它也可以。我不知道是什么原因引起了这个问题。欢迎任何帮助。

非常感谢!

0 个答案:

没有答案