我有一个多维数组i:
Array
(
[0] => Array
(
[title_0] => Sample Gift product 5
[qty_0] => 1.0000
)
[1] => Array
(
[title_1] => Sample Gift product 2
[qty_1] => 5.0000
)
[2] => Array
(
[title_2] => Sample Gift product 5
[qty_2] => 1.0000
)
[3] => Array
(
[title_3] => Sample Gift product 2
[qty_3] => 1.0000
)
)
但是我想要这样的结果,如果任何title元素在数组中具有相同的值应删除但是必须添加它们的qty值。最终数组应该看起来像
Array
(
[0] => Array
(
[title_0] => Sample Gift product 5
[qty_0] => 2.0000
)
[1] => Array
(
[title_1] => Sample Gift product 2
[qty_1] => 6.0000
)
)
请帮助我,我被困在这里不知道如何处理。感谢
答案 0 :(得分:0)
制作一个包含$arrayAll[$title] = $quantity;
的新数组
循环原始数组,如果没有设置初始数量,如果有标题添加数量的键。
<?php
$aAll = array();
foreach ($multyArray as $i => $data) {
$title = $data['title_'.$i];
if( ! isset($aAll[$title] ) $aAll[$title] = 0;
$aAll[$title] += $data['qty_'.$i];
}
// now you can recreate your original multy array with unique titles and added quantities.
此外,您不需要使用title_0
和qty_0
,只需使用title和qty,因为它们是该阵列的唯一键。