按列对二维数组的行进行分组[重复]

问题描述 投票:0回答:2

在下面的多维数组中,我想合并具有相同 merge_id 的数组。我不确定“合并”是正确的词:在下面的示例中, array['0'] 应该变成 array['0'] ,其中包含 array['0']['0'] 和 array[' 0']['1'],后者等于数组['1']。我希望这是有道理的......

数组来自按 merge_id 排序的数据库,因此具有匹配 merge_id 的数组始终彼此“相邻”,并且永远只有 2 个具有相同的 merge_id

当我循环遍历数组时,我知道我需要保留一个始终等于前一个 merge_id 的变量,如果前一个和当前之间存在匹配,则合并。

Array
(
    [0] => Array
        (
            [client_id] => 5
            [company_name] => company111_name
            [id] => 3
            [fee] => 111
            [year] => 2009
            [quarter] => 3
            [date_inserted] => 1264948583
            [description] => 2009 - Q3


            [fee_type] => 
            [merge_id] => a87ff679a2f3e71d9181a67b7542122c
            [total_paid] => 0
            [total_remainder] => 0
        )

    [1] => Array
        (
            [client_id] => 5
            [company_name] => company111_name
            [id] => 6
            [fee] => 55.5
            [year] => 2010
            [quarter] => 2
            [date_inserted] => 1264949470
            [description] => 2010 - Q2


            [fee_type] => 
            [merge_id] => a87ff679a2f3e71d9181a67b7542122c
            [total_paid] => 0
            [total_remainder] => 0
        )

    [2] => Array
        (
            [client_id] => 5
            [company_name] => company111_name
            [id] => 4
            [fee] => 111
            [year] => 2009
            [quarter] => 4
            [date_inserted] => 1264948583
            [description] => 2009 - Q4


            [fee_type] => 
            [merge_id] => 
            [total_paid] => 0
            [total_remainder] => 0
        )

    

    [3] => Array
        (
            [client_id] => 5
            [company_name] => company111_name
            [id] => 7
            [fee] => 55.5
            [year] => 2010
            [quarter] => 3
            [date_inserted] => 1264949470
            [description] => 2010 - Q3


            [fee_type] => 
            [merge_id] => 
            [total_paid] => 0
            [total_remainder] => 0
        )

)

代码

$merger = $data['search']['0']['merge_id'];
$i = 0;
foreach ($data['search'] as $fee) {
    if ($fee['merge_id'] == $merger) {
        //bump up & merge arrays
        ???
    }
    $merger = $fee['merge_id'];
    $i++;
}
php arrays multidimensional-array grouping sub-array
2个回答
4
投票

您可以使用 ID 作为键,将具有相同 ID 的所有项目放入同一个数组中:

$merged = array();
foreach ($data['search'] as $fee) {
    if ($fee['merge_id'] == '') {
        continue;
    }
    if (!isset($merged[$fee['merge_id']])) {
        $merged[$fee['merge_id']] = array();
    }
    $merged[$fee['merge_id']][] = $fee;
}
$merged = array_values($merged);

请注意,这将跳过合并 ID 为空的项目。在这种情况下,您还可以使用默认合并 ID,将

continue;
替换为
$fee['merge_id'] = 0;


1
投票
  foreach($array as $p)
      $result[$p['merge_id']][] = $p;
© www.soinside.com 2019 - 2024. All rights reserved.