假设我有一个这样的数组:
Array
(
(
[0] => A
[1] => 20
)
(
[0] => B
[1] => 10
)
(
[0] => G
[1] => 5
)
(
[0] => A
[1] => 15
)
)
我想删除重复的值并只汇总一行数组:我想要的:
Array
(
(
[0] => A
[1] => 35 // <= sum : 20 + 15
)
(
[0] => B
[1] => 10
)
(
[0] => G
[1] => 5
)
)
我的代码:
while($row = $stmt->fetch()){
$arr = array(
'GoodMainCode'=>persian_sql_to_php($row['GoodMainCode']), // <= like A in the example
'title'=> persian_sql_to_php($row['GoodName']),
'author'=>persian_sql_to_php($row['moalef']),
'publisher'=>persian_sql_to_php($row['Nasher']),
'translator'=>persian_sql_to_php($row['Motarjem']),
'price'=>persian_sql_to_php($row['SellPrice1']),
'isbn'=>persian_sql_to_php($row['ISBN']),
'amount'=>persian_sql_to_php($row['Amount']), // <= if GoodMainCode is same key, I must sum it.
'year_of_publish'=>persian_sql_to_php($row['SaleChap']),
'period_print'=>persian_sql_to_php($row['NobateChap'])
);
array_push($mjson,$arr);
}
//to remove duplicate values and sum amount key values
foreach($mjson as $v){
if(!isset($result[$v['GoodMainCode']]))
$result[$v['GoodMainCode']] = $v;
else
$result[$v['GoodMainCode']]['amount'] += $v['amount'];
}
但我的foreach
创造了额外的价值!
它会创建一个GoodMainCode
值。
我的输出:
(要将输出复制/粘贴读入http://json.parser.online.fr/):
{"7916":{"id":"1168","GoodMainCode":"7916","title":"\u0632\u064a\u0631\u062f\u0633\u062a\u064a \u0637\u0644\u0642\u064a CLIP BOARD","author":" ","publisher":"\u0641\u0642\u064a\u0647\u064a \u0645\u0647\u0631","translator":" ","price":"20625","isbn":" ","amount":"0","year_of_publish":"0","period_print":"0"},"7989":{"id":"16827","GoodMainCode":"7989","title":"\u064a\u062f\u0643 \u0627\u062a\u0648\u062f5\u0645\u064a\u0644 \u0643\u0648\u0647 \u0646\u0648\u0631B6","author":" ","publisher":"","translator":" ","price":"108025","isbn":" ","amount":61,"year_of_publish":"0","period_print":"0"},"8350":{"id":"1225","GoodMainCode":"8350","title":"\u064a\u062f\u0643 \u0627\u062a\u0648\u062f\u0637\u0631\u0627\u062d\u064a2\u0645\u064a\u0644JBN","author":" ","publisher":"","translator":" ","price":"3375","isbn":" ","amount":"0","year_of_publish":"0","period_print":"0"}}
在我的输出中,7916
,7989
,8350
是额外的。
答案 0 :(得分:0)
可能有一种更快的方式,但这是实现它的一种方法(种类)。
$array = array(
array('A', 20),
array('B', 10),
array('C', 5),
array('A', 15),
);
$sum_array();
foreach ($array as $internal_array)
{
// using the letter here as a key, so we can increment that value using += operator
$sum_array[$internal_array[0]] += $internal_array[1];
}
// gives you (not exactly what you want but more manageable in my opinion)
/*
[
'A' => 35,
'B' => 10,
'C' => 15,
]
*/
当然,这要求您的多维数组是一致的,并且始终具有键和值对。