Rafael Shkembi - 1 year ago 75

PHP Question

I have using a foreach inside a function but i could not output the correct value from it.

This is what i have try

First i have a array that has all the data i want

`//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

)

)

And here is the function that collects the sum of "ctr_tot" key

`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;

}

and here i call the function

`kontratat_tot("grup_1");`

I have been looking for the past 3 hours to find any solution for my problem but i have stuck and even if the solution is in from of my eyes i could not see it..

That is why iam looking for your help.

Thanks all

Answer Source

Your function is trying to access `$kontrata`

which is not in current scope, but in parent scope.

I suggest you to pass your data as an argument, defining global variable and accessing it inside function will limit you to use that same variable name, if you suppose to use this function twice or more.

```
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;
}
```