组合同一关联键的数组值

时间:2018-01-24 16:32:43

标签: php arrays

我已经有了这个数组,我想循环遍历它,并将相同OrderDate上的价值加起来。其他值,比如我想要添加为子数组的折扣代码。

   array(3) {
      [0]=>
      array(4) {
        ["OrderDate"]=>
        string(10) "2018-01-01"
        ["DiscountCode"]=>
        NULL
        ["TotalRevenue"]=>
        string(9) "147618.76"
        ["Discount_Revenue"]=>
        string(8) "13453.77"
      }
      [1]=>
      array(4) {
        ["OrderDate"]=>
        string(10) "2018-01-01"
        ["DiscountCode"]=>
        string(6) "SALE38"
        ["TotalRevenue"]=>
        string(8) "364.92"
        ["Discount_Revenue"]=>
        string(8) "4083.64"
      }
      [2]=>
      array(4) {
        ["OrderDate"]=>
        string(10) "2018-01-01"
        ["DiscountCode"]=>
        string(9) "WELCOME20"
        ["TotalRevenue"]=>
        string(6) "113.83"
        ["Discount_Revenue"]=>
        string(6) "113.83"
      }
    }

所以应该看起来像:

 array(3) {
          [0]=>
          array(4) {
            ["OrderDate"]=>
            string(10) "2018-01-01"
            ["DiscountCodes"]=> array {
            [0] => "DISCOUNT"
            [1] => "SALE38"
            [2] => "WELCOME20"
             )
            ["TotalRevenue"]=>
            string(9) "147618.76"
            ["Discount_Revenue"]=>
            string(8) "13453.77"
          }
        }

我相信我已经使用此循环修复了它,如果密钥存在则添加到数组中。不确定这是否是最有效的方法呢?

    foreach ($results as $k => $result){

        if( array_key_exists($result['OrderDate'], $arr)){

            $arr[$result['OrderDate']]['price'] += $result['TotalRevenue'];
            $arr[$result['OrderDate']]['new'] =  false;


        } else {
            $arr[$result['OrderDate']] = array(
                'price' => $result['TotalRevenue'],
                'new' => true
            );
        }


    }

1 个答案:

答案 0 :(得分:0)

如果有其他人需要,我会找到自己的解决方案。

    $arr = array();

    foreach ($results as $k => $result){

        if( array_key_exists($result['OrderDate'], $arr)){

            $arr[$result['OrderDate']]['Total_Revenue'] += $result['TotalRevenue'];
            $arr[$result['OrderDate']]['Discount_Revenue'] += $result['Discount_Revenue'];
            isset($result['DiscountCode']) ? $arr[$result['OrderDate']]['Discount_Code'][] = $result['DiscountCode'] : '';
            $arr[$result['OrderDate']]['new'] =  false;


        } else {
            $arr[$result['OrderDate']] = array(
                'Total_Revenue' => $result['TotalRevenue'],
                'Discount_Revenue' => $result['Discount_Revenue'],
                'new' => true
            );
            isset($result['DiscountCode']) ? $arr[$result['OrderDate']]['Discount_Code'][] = $result['DiscountCode'] : '';
        }


    }