迭代数组中的前30个键

时间:2016-09-07 12:43:38

标签: php arrays

我有一个存储在名为$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"
    }

我得到所有Closing值的算术平均值,如下所示:

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

问题是,现在我只需要阵列中的前30个键,但我不知道该怎么做,有人可以帮我吗?我尝试过for循环,但它没有做到这一点。有任何想法吗?提前感谢大家的时间和帮助。

5 个答案:

答案 0 :(得分:3)

使用你的第二段代码:

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

添加 && $total < 30 应该可以解决问题,因为您需要计算添加的项目数量。

<小时/> 如果你不想在一个额外条件下做额外的循环,你可以突破for
(感谢 Adam 指出这一点)

foreach ($data->data as $obj) {
    if (isset($obj->Closing) && $total < 30) {
        // ...
    }
    else if ($total >= 30) break;
}

答案 1 :(得分:2)

要获取数组的前N个元素,请使用array_slice()函数。

$output = array_slice($input, 0, 30);

答案 2 :(得分:1)

目前的答案存在的问题是,当它达到30时,它实际上不会脱离循环。当然,当$ total = 30时,它只是一个爆发的情况?

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

foreach ($data->data as $obj) {
    if (isset($obj->Closing)) { 
        $sum += $obj->Closing;
        $total++;
        if($total==$max){
            break;
        }  
    }
}

答案 3 :(得分:1)

所以有一种古老的学校做事方式称为for循环。

$dataArray = $data->data;

for($i = 0; $i <= 30; $i++){
    $obj = $dataArray[$i]; //Just like the object you have.
    //Do your thing with $obj.
    //Loop will only run 30 times
}

我不确定数组的结构,但$data->data似乎是一个数组。

答案 4 :(得分:0)

如果你喜欢迭代器。你可以结合使用CallbackFilterIterator和LimitIterator

$iterator = new ArrayIterator($data->data);
$filtered = new CallbackFilterIterator($iterator, function ($current, $key, $iterator) {
    return isset($current->Closing);
});
//now $filtered have only objects with Closing property
$limited = new LimitIterator($filtered, 0, 30);
$sum = 0;
foreach ($limited as $obj) {
    $sum += $obj->Closing;
}
echo $sum/iterator_count($limited);