简体   繁体   English

如何将新的索引和值推送到php数组?

[英]How to push new index and value to php array?

I am fetching data from a table using group by payment method. 我正在使用按付款方式分组从表中获取数据。 What happen is in group by the data comes up corresponding to those data only which are in table . 分组中发生的数据仅与表中的那些数据相对应。 But I want all payment types to be shown in result . 但我希望在结果中显示所有付款类型。 I am using following query. 我正在使用以下查询。

 $query = "select  paytype ,sum(totalamount)  from `tbl_payments` group by paytype";

There are 5(cash,credit,paypal..) types of payment . 有5种(现金,信用,贝宝..)付款方式。 I want all the payment methods with the result , so that if paytype is not find by query result it should be appended like ['credit'] =>[0] , means paytype => amount(which should be 0 at that case) . 我希望所有付款方式都带有结果,因此,如果在查询结果中未找到paytype,则应将其附加为['credit'] =>[0] ,表示paytype => amount(which should be 0 at that case)

Please help me on this. 请帮我。

You didn't tell about the table paytype containing the list of valid payment methods. 你没有告诉表paytype含有的有效支付方式列表。

To get all the payment methods in the result, you must use a left join. 要获得结果中的所有付款方式,您必须使用左联接。 Something like : 就像是 :

select pt.paytype, sum(p.totalamount)
from `tbl_paytypes` pt
left join `tbl_payments` p 
on pt.paytype = p.paytype 
group by pt.paytype

使用左联接和paymettypes表获取所有付款类型

Best way is to use entity class, ex. 最好的方法是使用实​​体类。

class PaymentTypes{  private $cash;  private $credit;  private $paypal;  ....

//constructor

//setters and getters }

in constructor you can set a default parameters for the fields if you dont get any values 在构造函数中,如果未获取任何值,则可以为字段设置默认参数

public function __construct($array){   $someDefaultValue = '';   if(!empty($array['name_of_column_in_databaseTable'])){   $this->$cash
= $array['name_of_column_in_databaseTable'];  }else{   $this->$cash = $someDefaultValue; } ... }

Result from database is like array(array(), array(), ...) 数据库的结果就像array(array(),array(),...)

so you can make: 这样您就可以:

foreach($result as $key=>$value){
 $paymentTypes[] = new PaymentTypes($value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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