如何使用PHP计算数组中的所有索引值?

时间:2016-06-09 08:33:36

标签: php

我想加上PHP中数组的所有索引值

我检索数据如下

$c = $loan->data->lists('principal');
var_dump($c);'

array (size=34)
  0 => string '0.0000' (length=6)
  1 => string '1600.0000' (length=9)
  2 => string '1600.0000' (length=9)
  3 => string '1600.0000' (length=9)
  4 => string '1600.0000' (length=9)
  5 => string '1600.0000' (length=9)
  6 => string '0.0000' (length=6)
  7 => string '0.0000' (length=6)
  8 => string '0.0000' (length=6)
  9 => string '0.0000' (length=6)
  10 => string '0.0000' (length=6)
  11 => string '1600.0000' (length=9)
  12 => string '1600.0000' (length=9)
  13 => string '1600.0000' (length=9)
  14 => string '1600.0000' (length=9)
  15 => string '1600.0000' (length=9)
  16 => string '0.0000' (length=6)
  17 => string '0.0000' (length=6)
  18 => string '0.0000' (length=6)
  19 => string '0.0000' (length=6)
  20 => string '0.0000' (length=6)
  21 => string '0.0000' (length=6)
  22 => string '0.0000' (length=6)
  23 => string '1600.0000' (length=9)
  24 => string '1600.0000' (length=9)
  25 => string '0.0000' (length=6)
  26 => string '0.0000' (length=6)
  27 => string '0.0000' (length=6)
  28 => string '0.0000' (length=6)
  29 => string '1600.0000' (length=9)
  30 => string '1600.0000' (length=9)
  31 => string '1600.0000' (length=9)
  32 => string '0.0000' (length=6)
  33 => string '0.0000' (length=6)

3 个答案:

答案 0 :(得分:2)

像这样使用

<?php
$a=array("1"=>"test","5"=>"test2","8"=>"test3");
$num=array_keys($a);
echo array_sum ( $num );
?>

Output : 14

答案 1 :(得分:2)

您可以先使用array_mapfloatval将数组值解析为浮点数:

View

然后执行array_sum获取总数:

$myArray = array_map('floatval', $myArray);

答案 2 :(得分:0)

我用它为我工作

 $c = $loan->payment->lists('paid_principal');
 $all = array_reduce($c, function($a, $b) { return $a + $b;  },0);
 dd($all);

array_sum 是更好的方法