如何在循环数组php

时间:2018-08-07 07:56:47

标签: php arrays

我有这样的数据dd($ arr):

enter image description here

我如何求和retweet_count值,例如233 + 2 = 235

4 个答案:

答案 0 :(得分:2)

您可以使用array_sum和array_column。
Array_column从多维数组中获取一个特定的项目列,并对其进行平面排列,然后array_sum对平面数组求和。

echo array_sum(array_column($arr, "retweet_count")); // 235

edit:我看到您的数组一直都不一样。您可能需要使用它来隔离状态。

echo array_sum(array_column($arr["statuses"], "retweet_count")); // 235

答案 1 :(得分:0)

$sumArray = array();
foreach ($myArray as $k=>$subArray){
 foreach ($subArray as $id=>$value){
  $sumArray[$id]+=$value;}
   }
   print_r($sumArray);

答案 2 :(得分:0)

Array
(
[0] => Array
    (
        [gozhi] => 2
        [uzorong] => 1
        [ngangla] => 4
        [langthel] => 5
    )

[1] => Array
    (
        [gozhi] => 5
        [uzorong] => 0
        [ngangla] => 3
        [langthel] => 2
    )

[2] => Array
    (
        [gozhi] => 3
        [uzorong] => 0
        [ngangla] => 1
        [langthel] => 3
    )
 )

答案 3 :(得分:0)

**You can use array_walk_recursive() to get a general-case solution for your problem (the 
 one when each inner array can possibly have unique keys).**

$final = array();
array_walk_recursive($input, function($item, $key) use (&$final){
$final[$key] = isset($final[$key]) ?  $item + $final[$key] : $item;
});

**Example with array_walk_recursive() for the general case**

array_sum(array_column($input, 'gozhi')); 


**Example with array_column() for the specified key**


 If you want to get the total sum of all inner arrays with the same keys (the desired 
 result that you've posted), you can do something like this (bearing in mind that the 
 first inner array must have the same structure as the others) :


  $final = array_shift($input);

  foreach ($final as $key => &$value){
  $value += array_sum(array_column($input, $key));
   }    

  unset($value);