如何将2个阵列组合成单个阵列?

时间:2016-02-28 10:10:03

标签: php arrays

我有2个数组,你会看到如下,我希望主题组合成一个。前2个数组具有一个总和和一个月的子数组。结果数组(第3个)必须具有同一个月的前2个数组的总和。

array:3 [
  0 => array:2 [
    "sum" => 179.0
    "month" => "2016-01"
  ]
  1 => array:2 [
    "sum" => 34.0
    "month" => "2016-02"
  ]
  2 => array:2 [
    "sum" => 67.0
    "month" => "2016-03"
  ]
]


array:2 [
  0 => array:2 [
    "sum" => 143.25
    "month" => "2016-01"
  ]
  1 => array:2 [
    "sum" => 479.0
    "month" => "2016-03"
  ]
]


Total:

array:3 [
  0 => array:3 [
    "sum" => 313.25
    "month" => "2016-01"
  ]
  1 => array:2 [
    "sum" => 34.0
    "month" => "2016-02"
  ]
  2 => array:2 [
    "sum" => 546.0
    "month" => "2016-03"
  ]
]

我尝试了什么:

for($i=0;$i<count($com1);$i++){
            for ($j=0; $j < count($com2); $j++) { 
                if($com1[$i]['month'] == $com2[$j]['month']){
                    $total = $com1[$i]['sum']+$com2[$j]['sum']
                }
            }
        }

但它没有给出我想要的结果

我是abit noob ...我希望有人可以提供帮助。感谢

2 个答案:

答案 0 :(得分:0)

试试这个:

$com1 = [
  0 => [
    'sum' => 179.0,
    'month' => '2016-01'
  ],
  1 => [
    'sum' => 34.0,
    'month' => '2016-02'
  ],
  2 => [
    'sum' => 67.0,
    'month' => '2016-03'
  ]
];

$com2 = [
  0 => [
    'sum' => 143.25,
    'month' => '2016-01'
  ],
  1 => [
    'sum' => 479.0,
    'month' => '2016-03'
  ]
];

$total = [];
foreach ($com1 as $data) {
    $total[$data['month']] = $data;
}

foreach ($com2 as $data) {
    if (!isset($total[$data['month']])) {
        $total[$data['month']] = [
            'sum' => 0,
            'month' => $data['month']
        ];
    }
    $total[$data['month']]['sum'] += $data['sum'];
}

print_r($total);

答案 1 :(得分:0)

这是一个生成非关联数组的解决方案(如您在问题中所示):

var localEndPoint = tcpClient.Client.LocalEndPoint as IPEndPoint;
var localAddress = localEndPoint.Address;
var localPort = localEndPoint.Port;

当$ data1和$ data2为:

$month_idx = []; // helper to identify at which index a certain month is stored
$result = [];
foreach (array_merge($data1, $data2) as $idx => $row) {
    $month = $row["month"];
    if (!isset($month_idx[$month])) {
        $month_idx[$month] = count($result);
        $result[] = $row;
    } else {
        $result[$month_idx[$month]]["sum"] += $row["sum"];
    }
}

var_export($result);

然后输出是:

$data1 = array (
    array(
        "sum" => 179.0,
        "month" => "2016-01"
    ),
    array(
        "sum" => 34.0,
        "month" => "2016-02"
    ),
    array(
        "sum" => 67.0,
        "month" => "2016-03"
    )
);
$data2 = array (
    array(
        "sum" => 143.25,
        "month" => "2016-01"
    ),
    array(
        "sum" => 479.0,
        "month" => "2016-03"
    )
);