php - Iterating through the first 30 keys in an array -
i have array stored variable called $data
["data"]=> array(413) { [0]=> object(stdclass)#254 (7) { ["energy"]=> string(7) "44555" ["closing"]=> string(10) "102" } [1]=> object(stdclass)#260 (7) { ["energy"]=> string(7) "2522" ["closing"]=> string(10) "854" }
and obtain arithmetic mean closing values this:
// initialize sum , total $sum = 0; $total = 0; foreach ($data->data $obj) { if (isset($obj->closing)) { // verify current object has closing $sum += $obj->closing; // add sum $total++; // increment count } } echo $sum / $total; // display average
the problem need first 30 key array, don't know how that, can me please? have tried loop doesn't trick. ideas? thank in advance time , help.
using second piece of code :
$sum = 0; $total = 0; foreach ($data->data $obj) { if (isset($obj->closing) && $total < 30) { // closing? + numofvalues < 30 ? $sum += $obj->closing; $total++; } } // display average echo $sum / $total;
adding && $total < 30
should trick since count how many items add.
can break out of
for
if don't want loops single condition :(thanks adam pointing out)
foreach ($data->data $obj) { if (isset($obj->closing) && $total < 30) { // ... } else if ($total >= 30) break; }
Comments
Post a Comment