简体   繁体   中英

Explode elements from mysql_fetch_array and sum them up

Am fetching memberID in form KE00033-00 where last two digits represent number of individuals in the members family.So far am able to get all memberID and explode them but am not able to sum them up. array_sum() outputs a wrong value. Here is the code:

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

Using explode will gives you an array containing values you need to convert the desires value like $entries[1] again to array to get the numbers to 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);
 }

or if you want to take the sum of all records you can simple use +=

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

 }
 echo $individuals;

str_split

array_sum

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM