Calculating the count of duplicates in an array goes wrong

  arrays, laravel, php

I currently have a bit of code that checks for duplicate lamps per order. It then adds the count of that lamp and removes the duplicates. These orders have a phase. In an export I want to get all the exports per phase and get the count of all the same lamps from all those orders. Currently only some of the lamps are calculated the right way, but sometimes the amount of lamps is doubled or has + 10 more than it should have. I can’t find the wrong piece in my code. Can anyone help me? This is the code I am talking about:

/**
 * @return Builder
 */
public function array(): array
{
    $orders = Order::where('phase', $this->phase)
        ->with('lamps')
        ->get()
        ->map(static function (Order $order) {
            $order->lamps->each(function (Lamp $lamp) {
                $countedLamps = DB::table('lamp_order')
                    ->where('order_id', $lamp['pivot']['order_id'])
                    ->select(DB::raw('*, count(*) as count_lamps'))
                    ->groupBy('lamp_id')
                    ->get();

                foreach ($countedLamps as $countedLamp) {
                    // If lamp_id is the same then add the count to the Lamp. 
                    if ($countedLamp->lamp_id == $lamp['id']) {
                        $lamp->count = $countedLamp->count_lamps;
                    }
                }
            });

            // Remove duplicate Lamps an create an new attribute in the collection array.
            $collection = collect($order->lamps);
            $order->ordered_lamps = $collection->unique()->values()->all();
            // Make unordered Lamps array hidden.
            $order->makeHidden('lamps');
            return $order;
        });

    $orderedLamps = [];

    foreach ($orders as $order) {
        foreach ($order['ordered_lamps'] as $orderedLamp) {
            $orderedLamps[] = $orderedLamp;
        }
    }

    $hash = array();
    $array_out = array();

    foreach ($orderedLamps as $item) {
        $hash_key = $item['id'] . '|' . $item['name'];
        if (!array_key_exists($hash_key, $hash)) {
            $hash[$hash_key] = sizeof($array_out);
            array_push($array_out, array(
                'id' => $item['id'],
                'name' => $item['name'],
                'fitting' => $item['fitting'],
                'light_color_code' => $item['light_color_code'],
                'article_number' => $item['article_number'],
                'count' => $item['count'],
            ));
        } else {
            $array_out[$hash[$hash_key]]['count'] += $item['count'];
        }
    }

    // Get lamps and count from order where phase == phase
    return $array_out;
}

If there is a better solution than this I also would like to hear I could improve this.

Source: Laravel

Leave a Reply