0

我正在获取 KE00033-00 表格中的 memberID,其中最后两位数字代表成员家庭中的人数。到目前为止,我能够获取所有 memberID 并将它们分解,但无法总结它们。array_sum() 输出错误值。这是代码:

 $query=mysql_query("SELECT * FROM subscribers");
  $arr = array();
  while($row=mysql_fetch_array($query)){
  $arr[] =$row['member'];
  }
  foreach ($arr as $value) 
    {
  $entries=explode('-',$value);
  print_r($entries)."<br>";//outputs the last two digits of memberID's
  echo array_sum($entries);
 }
4

2 回答 2

1
 There is no need of extra foreach loop there. Try this.
  $query=mysql_query("SELECT * FROM subscribers");
  $arr = array();
  $individual = array();
  while($row=mysql_fetch_array($query)){
    $arr =explode('-', $row['member']);
    $individual[] = $arr[1];
  }

  echo array_sum($individual);
 }
于 2013-09-06T10:03:18.033 回答
0

使用explodewill 为您提供一个包含值的数组,您需要将期望值$entries[1]再次转换为数组以获取数字sum

$query=mysql_query("SELECT * FROM subscribers");
  $arr = array();
  while($row=mysql_fetch_array($query)){
  $arr[] =$row['member'];
  } 
   $individuals=0;
  foreach ($arr as $value) 
  {
  $entries=explode('-',$value);
  print_r($entries[1])."<br>";//outputs 00 now you need to make array for this no to sum up
  $arr1 = str_split($entries[1]);

//  Array
//(
  //  [0] => 0
   // [1] => 0
//)
//Use array_sum to sum up the array values

 echo array_sum($arr1);
 }

或者如果您想获取所有记录的总和,您可以简单地使用+=

$individuals=0;
  foreach ($arr as $value) 
  {
 $entries=explode('-',$value);
 $individuals+= $entries[1];

 }
 echo $individuals;

str_split

数组总和

于 2013-09-06T10:04:46.037 回答