我每个月都有一张销售记录表。在这种情况下,每个推销员都有自己的代码bd
和nk
。
的MySQL
select sale_plc
, month(sale_date) as mon
, sum(sale_cost) as cost
from daily_sales
where year(sale_date)='2016'
group
by year(sale_date)
, month(sale_date)
, sale_plc
order
by month(sale_date)
, sale_plc asc
LIMIT 0, 30
在查询之后我得到了这个结果:
id mon cost
bd 1 224787
nk 1 721102
bd 2 440399
nk 2 898020
bd 3 363543
nk 3 878250
虽然
根据结果。我希望结果像这样的数组。 阵列
(
[1] => Array
(
[mon] => 1
[bd] => 224787
[nk] => 721102
)
[2] => Array
(
[mon] => 2
[bd] => 440399
[nk] => 898020
)
[3] => Array
(
[mon] => 3
[bd] => 363543
[nk] => 878250
)
)
我知道这与sale_plc
有关。我需要制作阵列,但我不知道这样做。
答案 0 :(得分:2)
我没有你的SQL输出,所以我创建一个数组并使用与我对你的数组相同的功能创建我自己的代码。
<强> PHP 强>
$arr = array(array("id" => "bd", "mon" => "1", "cost" => "224787"),
array("id" => "nk", "mon" => "1", "cost" => "721102"),
array("id" => "bd", "mon" => "2", "cost" => "440399"),
array("id" => "nk", "mon" => "2", "cost" => "898020"),
array("id" => "bd", "mon" => "3", "cost" => "363543"),
array("id" => "nk", "mon" => "3", "cost" => "878250"),
);
$output_arr = array();
$tmp = 0;
foreach($arr as $key => $value){
if($tmp == 0 || $tmp != $value['mon'])
$output_arr[$value['mon']][mon] = $value['mon'];
if($value['id'] == 'bd')
$output_arr[$value['mon']][$value['id']] = $value['cost'];
if($value['id'] == 'nk')
$output_arr[$value['mon']][$value['id']] = $value['cost'];
$tmp = $value['mon'];
}
echo "<pre>";
print_r($output_arr);
echo "</pre>";
<强>输出强>
Array
(
[1] => Array
(
[mon] => 1
[bd] => 224787
[nk] => 721102
)
[2] => Array
(
[mon] => 2
[bd] => 440399
[nk] => 898020
)
[3] => Array
(
[mon] => 3
[bd] => 363543
[nk] => 878250
)
)
我已经回答了你的SQL输出。给出了SQL的示例。
<强> PHP 强>
$output_arr = array();
//Your sql
$sql = "select sale_plc
, month(sale_date) as mon
, sum(sale_cost) as cost
from daily_sales
where year(sale_date)='2016'
group
by year(sale_date)
, month(sale_date)
, sale_plc
order
by month(sale_date)
, sale_plc asc
LIMIT 0, 30";
$tmp = 0;
$i = 0;
$qry = mysqli_query($conn, $sql);
while ($obj = mysqli_fetch_object($qry )){
if($tmp == 0 || $tmp != $obj->mon)
$output_arr[$obj->mon][mon] = $obj->mon;
if($obj->id == 'bd')
$output_arr[$obj->mon][$obj->id] = $obj->cost;
if($obj->id == 'nk')
$output_arr[$obj->mon][$obj->id] = $obj->cost;
$tmp = $obj->mon;
}
print_r($output_arr);
输出
Array(
[1] => Array
(
[mon] => 1
[bd] => 224787
[nk] => 721102
)
[2] => Array
(
[mon] => 2
[bd] => 440399
[nk] => 898020
)
[3] => Array
(
[mon] => 3
[bd] => 363543
[nk] => 878250
)
)
试试这个答案,如果有任何问题,请告诉我。