douling1936 2016-11-17 19:07
浏览 55

PHP / Laravel,foreach :( $ array as $ value)有效,($ array as $ key => $ value)不行?

I have no idea how to explain my question in another way as than by giving an example. Hope this is ok.

I defined two arrays:

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

and

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

then i try to get data from a given database like:

        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();
        };
    };

which works perfectly with an output like:

{

"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
}

}

I changed the $years array to:

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

and the query to:

        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();
        };
    };

what i got:

{

"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
}

}

and i have no idea why i get just "0"! When i try to debug and check the $year var, it still has the correct value. If I insert e.g. '2010' instead of $year in the ->whereyear(), it works as well. I have no idea what causes the problem. Any help welcome.

many thanks!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)