为什么我的数组表现得像这样

时间:2016-02-23 11:41:53

标签: php mysql arrays mysqli

while($pp_info = mysqli_fetch_array($sqlpinfo)){

           $product_title = $pp_info['book_name'];
           $books_image = $pp_info['book_upload'];
           $books_price = array($pp_info['book_price']);
 }

 Array ( [0] => 324 ) 
 Array ( [0] => 500 ) 
 Array ( [0] => 543 ) 
 Array ( [0] => 22 )

如何获得每个数字的总和?

我使用array_sum($books_price);

结果是324 500 543 22

3 个答案:

答案 0 :(得分:1)

您应该在mysql查询中使用SUM(book_price) As Total

SELECT SUM(column_name) FROM table_name;

查看此link了解更多详情。

PHP 中,

$book_total = 0;  // define variable outside loop
while($pp_info = mysqli_fetch_assoc($sqlpinfo)){
  $product_title = $pp_info['book_name'];
  $books_image = $pp_info['book_upload'];
  $books_price = $pp_info['book_price'];  
  $book_total += $books_price; // perform addition operation
}
echo "Book Total: $book_total";

希望它会对你有所帮助:)。

答案 1 :(得分:0)

您可以通过package com.parse.starter; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.parse.ParseAnalytics; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.SaveCallback; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ParseObject score = new ParseObject("Score"); score.put("username", "dinesh"); score.put("score", 123); score.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { if (e == null) { Log.i("info", "Successful"); } else { Log.i("info", "Unsuccessful"); e.printStackTrace(); } } }); ParseAnalytics.trackAppOpenedInBackground(getIntent()); } } 将所有图书价格收集到一个数组$books_price数组中,然后在循环后计算其总和

$books_price[] = $pp_info['book_price'];

答案 2 :(得分:0)

改变
while($pp_info = mysqli_fetch_array($sqlpinfo)){

           $product_title = $pp_info['book_name'];
           $books_image = $pp_info['book_upload'];
           $books_price = array($pp_info['book_price']);
 }

$bookpricearray = array();

while($pp_info = mysqli_fetch_array($sqlpinfo)){

             $product_title = $pp_info['book_name'];
             $books_image = $pp_info['book_upload'];
             array_push($bookpricearray,$pp_info['book_price']);
 }

echo $total_price=array_sum($bookpricearray);