[英]foreach inside a function doesn't output value
我在函數內部使用了foreach,但是無法從中輸出正確的值。
我有一個按功能處理的數組
//this is only a small part of it because it is very large
Array
(
[2016-05-02] => Array
(
[grup_1] => Array
(
[luce] => 4
[ctr_ok] => 3
[ctr_tot] => 7
[ctr_ko] => 4
[gas] => 3
[ore] => 30.5
)
[grup_2] => Array
(
[luce] => 3
[ctr_ko] => 4
[ctr_tot] => 6
[gas] => 3
[ctr_ok] => 2
[ore] => 47
)
[grup_3] => Array
(
[luce] => 6
[ctr_ko] => 1
[ctr_tot] => 8
[ctr_gia_cliente] => 1
[ctr_ok] => 6
[gas] => 2
[ore] => 24
)
[grup_4] => Array
(
[luce] => 4
[ctr_ok] => 4
[ctr_tot] => 8
[gas] => 4
[ctr_ko] => 4
[ore] => 30
)
[grup_5] => Array
(
[luce] => 9
[ctr_ko] => 11
[ctr_tot] => 17
[gas] => 8
[ctr_ok] => 6
[ore] => 35
)
[grup_6] => Array
(
[luce] => 1
[ctr_ok] => 2
[ctr_tot] => 2
[gas] => 1
[ore] => 36
)
[grup_7] => Array
(
[luce] => 5
[ctr_ko] => 1
[ctr_tot] => 7
[ctr_ok] => 6
[gas] => 2
[ore] => 22
)
)
[2016-05-03] => Array
(
[grup_1] => Array
(
[luce] => 6
[ctr_ok] => 6
[ctr_tot] => 10
[gas] => 4
[ctr_ko] => 4
[ore] => 33.5
)
[grup_2] => Array
(
[luce] => 6
[ctr_ok] => 4
[ctr_tot] => 8
[ctr_ko] => 2
[gas] => 2
[ctr_att_green] => 2
[ore] => 36
)
[grup_3] => Array
(
[luce] => 6
[ctr_ok] => 4
[ctr_tot] => 9
[gas] => 3
[ctr_ko] => 5
[ore] => 36
)
[grup_4] => Array
(
[luce] => 5
[ctr_ko] => 2
[ctr_tot] => 10
[gas] => 5
[ctr_ok] => 8
[ore] => 42
)
[grup_5] => Array
(
[gas] => 2
[ctr_ok] => 3
[ctr_tot] => 3
[luce] => 1
[ore] => 23
)
[grup_6] => Array
(
[luce] => 1
[ctr_ko] => 2
[ctr_tot] => 2
[gas] => 1
[ore] => 36
)
[grup_7] => Array
(
[luce] => 2
[ctr_ok] => 1
[ctr_tot] => 3
[ctr_gia_cliente] => 2
[gas] => 1
[ore] => 27.3
)
)
這是收集ctr_tot
鍵總和的ctr_tot
function kontratat_tot($grup_name){
$total = 0;
foreach ($kontrata as $date => $grup){
if($grup[$grup_name]['ctr_tot'] != 0){
$total += $grup[$grup_name]['ctr_tot'];
}
}
return $total;
}
在這里我調用函數
kontratat_tot("grup_1");
在過去的3個小時中,我一直在尋找解決問題的任何方法,但我一直堅持不懈,即使從我的眼中可以看到解決方案,我也看不到它。
您的函數正在嘗試訪問不在當前范圍內但在父范圍內的$kontrata
。
我建議您將數據作為參數傳遞,定義全局變量並在函數內部訪問它會限制您使用相同的變量名(如果您打算兩次或多次使用此函數)。
function kontratat_tot($kontrata, $grup_name){
$total = 0;
foreach ($kontrata as $date => $grup){
if($grup[$grup_name]['ctr_tot'] != 0){
$total += $grup[$grup_name]['ctr_tot'];
}
}
return $total;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.