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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀