Group identical items in PHP array & count

后端 未结 2 404
予麋鹿
予麋鹿 2021-01-26 03:21

I\'m trying to create an array that groups together similar/identical items and creates a count/ tally of the number of times that item occurs.

I\'ve managed to get an a

相关标签:
2条回答
  • 2021-01-26 03:35

    The outer part of your loop looks like it should work for this. You just need to make a couple of changes to how it is building the grouped array.

    foreach ($orders as $order) {
        foreach ($order['lineItems']['elements'] as $item) {
            // use the item id as a key in the array you are building
            $id = $item['item']['id'];
    
            if (isset($products[$id])) {
                // if the item has already been added, increment the count
                $products[$id]['Count']++;
            } else {
                // otherwise, add the item with an initial count of 1
                $products[$id]['ID'] = $id;
                $products[$id]['Item'] = $item['name'];
                $products[$id]['Count'] = 1;
            }
        }
    }
    

    The resulting $products array will have item IDs as keys. If you want it to have numeric keys instead, you can then do:

    $products = array_values($products);
    
    0 讨论(0)
  • 2021-01-26 03:37

    You want counts by id. Use a separate array, keyed by id to do this.

    $itemCounts = array();
    foreach($products as $product)
    {
        if (!isset($itemCounts[$product['code']]))
        {
            $itemCounts[$product['code']] = 0;
        }
        $itemCounts[$product['code']]++;
    }
    print_r($itemCounts);
    

    If you want, you can get everything in a single array, still keyed by ID:

    $itemCounts = array();
    foreach($products as $product)
    {
        if (!isset($itemCounts[$product['code']]))
        {
            $itemCounts[$product['code']] = array(
                'name' => $product['name'],
                'count' => 0
            );
        }
        $itemCounts[$product['code']]['count']++;
    }
    print_r($itemCounts);
    

    You can optimize this by not creating $products at all. Replace $products in my code above with the corresponding item from the original $orders array.

    EDIT

    The code snippets above give you the correct array structure to handle this type of data. To produce your exact desired output from the second code snippet above, you'd want to do something like this:

    foreach($itemCounts as $code => $item)
    {
        print $code . " " . $item['name'] . " " . $item['count'] . "\n";
    }
    
    0 讨论(0)
提交回复
热议问题