带索引的php数组操作

时间:2013-02-05 08:40:13

标签: php arrays sum

我有一个数组,我每行使用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

)

6 个答案:

答案 0 :(得分: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']);

答案 1 :(得分: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

分组

答案 2 :(得分: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);
?>

答案 3 :(得分:0)

使用array_merge_recursive()

这是做这件事的最佳选择

答案 4 :(得分: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'];
}

答案 5 :(得分: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']);
    }
  }
}