-1

I have an array with objects like below:

array:113 [
  0 => App\Api\Wheel {#5809
    -manufacturer: "RIAL"
    -colour: "diamant"
    -design: "aaaaaa"
    -surface: "ss"
    -diameter: 16
  }
  1 => App\Api\Wheel {#6201
    -manufacturer: "RIAL"
    -colour: "diamant"
    -design: "aaaaaa"
    -surface: "ss"
    -diameter: 17
  }

Here, based on the value, I need to group. Diameter is going to be different and others are going to be same.

My final result is to be same structure but diameter in array or comma separated string.

array:113 [
    0 => App\Api\Wheel {#5809
    -manufacturer: "RIAL"
    -colour: "diamant"
    -design: "aaaaaa"
    -surface: "ss"
    -diameter: [
            16,
            17      
        ]
    }

So far, I have tried following lines of code,

$finalResult = array();
        foreach ($records as $record) {
            if (!in_array($record->getManufacturer(), array_keys($finalResult))) {
                $finalResult[$record->getManufacturer()] = (object)array(
                    'manufacturer' => $record->getManufacturer(),
                    'colour' => $record->getColour(),
                    'design' => $record->getDesign(),
                    'surface' => $record->getSurface(),
                    'diameter' => $record->getDiameter()
                );
            } else {
                $finalResult[$record->getManufacturer()]->diameter = [$record->getDiameter()];
            }
        }
        dd(($finalResult));

But, I can not able to group by or return result into same format.

Can any body please help me?

nas
  • 2,289
  • 5
  • 32
  • 67

1 Answers1

1

You need to update the code in your else block to deal with adding another diameter value, at present you are just overwriting the existing value. To make an array, something like this:

if (is_array($finalResult[$record->getManufacturer()]->diameter)) {
    $finalResult[$record->getManufacturer()]->diameter[] = $record->getDiameter();
}
else {
    $finalResult[$record->getManufacturer()]->diameter = array($finalResult[$record->getManufacturer()]->diameter, 
                                                               $record->getDiameter());
}

To make a comma-separated list is a bit easier:

$finalResult[$record->getManufacturer()]->diameter .= ',' . $record->getDiameter();

Note that

!in_array($record->getManufacturer(), array_keys($finalResult))

can be replaced by

!isset($finalResult[$record->getManufacturer()])

which will be much faster.

Nick
  • 138,499
  • 22
  • 57
  • 95