1

我有一个数组,每行使用 mysql 查询获取,每个包含相同的索引,它看起来如下

array(

    0=> array(
         'order_nr'=> 123,
         'order_date' => '2013-01-29 00:00:00',
         'prod_name' => 'prod_1',
         'prod_value' => 1200

       )

    1=> array(
         'order_nr'=> 123,
         'order_date' => '2013-01-29 00:00:00' ,
         'prod_name' => 'prod_2',
         'prod_value' => 2100
    )

)

我想合并主题并计算 prod_value 的总和并在 prod_name 上创建一个新数组,最后我将拥有单个数组。我将如何在 php 中执行此操作,或者在这种情况下最好的解决方法是什么

array(
 'order_nr'=> 123,
 'order_date'=>'2013-01-29 00:00:00',
 'prod_name'=> array('prod_1', 'prod_2')
 'prod_value' => 3300

)
4

6 回答 6

1

如果产品列表不必是数组,您可以使用 Mysql 和聚合函数。它会是这样的:

SELECT order_no, order_data, GROUP_CONCAT(prod_name SEPARATOR ',') as prod_name, 
    SUM(prod_value) as prod_val FROM Products WHERE ... GROUP BY order_no;

如果您需要产品名称作为数组,则可以分解字符串:

explode(',', $row['prod_name']);
于 2013-02-05T09:00:11.273 回答
0
$aReturn = array();

foreach( $aData as $entry ) {
 if( empty($aReturn[$entry['order_nr']]) ) {
  $entry['prod_name'] = (array) $entry['prod_name'];
  $aReturn[$entry['order_nr']] = $entry;

  continue;
 }

 $aReturn[$entry['order_nr']]['prod_name'][] = $entry['prod_name'];
 $aReturn[$entry['order_nr']]['prod_value'] += $entry['prod_value'];
}

这将分组order_nr

于 2013-02-05T08:54:21.537 回答
0
<?php

$arr = array(0=> array(
                         'order_nr'=> 123,
                         'order_date' => '2013-01-29 00:00:00',
                         'prod_name' => 'prod_1',
                         'prod_value' => 1200

                       ),
            1=> array(
                         'order_nr'=> 123,
                         'order_date' => '2013-01-29 00:00:00' ,
                         'prod_name' => 'prod_2',
                         'prod_value' => 2100
                    )

            );

$sigle_arr = array();   
foreach($arr as $val){
   $sigle_arr[$val['order_nr']]['order_nr']     = $val['order_nr'];
   $sigle_arr[$val['order_nr']]['order_date']   = $val['order_date'];
   $sigle_arr[$val['order_nr']]['prod_name'][]  = $val['prod_name'];
   $sigle_arr[$val['order_nr']]['prod_value']  += $val['prod_value'];

}
print_r($sigle_arr);
?>
于 2013-02-05T08:54:52.500 回答
0

使用array_merge_recursive()

这是最好的选择

于 2013-02-05T08:57:48.550 回答
0
$newarray = array();
foreach($array as $v){
 if(!isset($newarray['order_nr'])){ 
 $newarray['order_nr'] = $v['order_nr'];
 }
 if(!isset($newarray['order_date'])){ 
 $newarray['order_date'] = $v['order_date'];
 }
 $newarray['prod_name'][] = $v['prod_name'];

 $newarray['prod_value'] = $newarray['prod_value'] + $v['prod_value'];
}
于 2013-02-05T09:02:04.493 回答
0
$temp = Users::find('all', array('conditions' => array('status' => array('$elemMatch' => array('fields' => array('temp')));
foreach($whichs as $which)
{
  foreach($which['temps'] as $temp)
  {
    if($temp['_id'] == $status['temp'])
    {
    array_push($tempsArray,$temp['status']);
    }
  }
}
于 2013-02-05T09:12:55.480 回答