在下面的多维数组中,我想合并具有相同merge_id的数组。我不确定“merge”是否是正确的单词:在下面的示例中,数组['0']应该成为数组['0'],其中包含数组['0'] ['0']和数组[' 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++;
}
答案 0 :(得分: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的项目。在这种情况下,您也可以使用continue;
替换$fee['merge_id'] = 0;
来使用默认合并ID。
答案 1 :(得分:1)
foreach($array as $p)
$result[$p['merge_id']][] = $p;