A problem with foreach in PHP
$list = Array (
Array (' id ' = = 1, ' count ' = 1),
Array (' id ' = = 1, ' count ' = 2),
Array (' id ' = = 2, ' count ' = 2),
Array (' id ' = = 3, ' count ' = 3),
Array (' id ' = = 3, ' count ' = + 4)
);
$sort = Array ();
foreach ($list as $v)
{
$sort [] = $v [' id '];
}
$sort = Array_unique ($sort);
$new = Array ();
foreach ($sort as $v 1)
{
$c = 0;
foreach ($list as $v 2)
{
if ($v 1 = = $v 2[' id '])
{
$c + = $v 2[' count '];
}
}
$new [] = array (' id ' = = $v 1, ' count ' = $c);
}
This is now the practice of seeking a simpler and more reasonable approach!!
Requirement: Existing array: $list, the result needed: Merge the field count for the duplicate ID in the array. As the above result array $new
------to solve the idea----------------------
$list = Array (
Array (' id ' = = 1, ' count ' = 1),
Array (' id ' = = 1, ' count ' = 2),
Array (' id ' = = 2, ' count ' = 2),
Array (' id ' = = 3, ' count ' = 3),
Array (' id ' = = 3, ' count ' = + 4)
);
Perform calculations
$tmp = Array ();
foreach ($list as $val) {
if (Isset ($tmp [$val [' ID ']]) {
$tmp [$val [' ID ']] + = $val [' count '];
}else{
$tmp [$val [' id ']] = $val [' count '];
}
}
Ksort ($TMP); Sort by key
$new = Array ();
foreach ($tmp as $k = = $v) {
Array_push ($new, array (' id ' = $k, ' count ' = $v));
}
Print_r ($new);
------to solve the idea----------------------
$list = Array (
Array (' id ' = = 1, ' count ' = 1),
Array (' id ' = = 1, ' count ' = 2),
Array (' id ' = = 2, ' count ' = 2),
Array (' id ' = = 3, ' count ' = 3),
Array (' id ' = = 3, ' count ' = + 4)
);
$new = Array ();
foreach ($list as $r) {
if (! isset ($new [$r [' ID ']]) $new [$r [' id ']] = $r;
else $new [$r [' id ']][' count '] + = $r [' count '];
}
$new = Array_values ($new);
Print_r ($new);
Array
(
[0] = = Array
(
[id] = 1
[Count] = 3
)
[1] = = Array
(
[id] = 2
[Count] = 2
)
[2] = = Array
(
[id] = 3
[Count] = 7
)
)