A related problem with foreach in PHP

Source: Internet
Author: User
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
)

)
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.