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 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起