doujieyu7062 2016-09-07 12:43 采纳率: 0%
浏览 52
已采纳

迭代数组中的前30个键

I have an array stored into a 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 I obtain an arithmetic mean for all the Closing values like this:

// initialize sum and total
$sum = 0;
$total = 0;

foreach ($data->data as $obj) {
    if (isset($obj->Closing)) {   // verify that the current object has a Closing
        $sum += $obj->Closing;    // add it to the sum
        $total++;                  // increment the count
    }
}
echo $sum / $total;                // display the average

The problem is that now I will only need the first 30 key from the array, but I don't know how to do that, can anyone help me please? I have tried with a for loop but it doesn't do the trick. Any ideas? Thank you all in advance for your time and help.

  • 写回答

5条回答 默认 最新

  • dongyongkui6329 2016-09-07 12:45
    关注

    Using your second piece of code :

    $sum = 0;
    $total = 0;
    
    foreach ($data->data as $obj) {
        if (isset($obj->Closing) && $total < 30) {   // Closing? + numOfValues < 30 ?
            $sum += $obj->Closing;
            $total++;
        }
    }
    
    // Display the average
    echo $sum / $total;
    

    Adding && $total < 30 should do the trick since you count how many items you add.


    You can break out of the for if you don't want to do extra loops with a single extra condition :
    (thanks Adam for pointing this out)
    foreach ($data->data as $obj) {
        if (isset($obj->Closing) && $total < 30) {
            // ...
        }
        else if ($total >= 30) break;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?