Skip to content
Advertisement

How to group a column into comma-separated string based on multiple common key value pair?

This is my updated question. I have an array of objects like below:

array:113 [
  0 => DataEntity {#1024
    -manufacturer: "Test1"
    -colour: "polar-silber"
    -design: "Bavaro"
    -diameter: 17
  }
  1 => DataEntity {#1524
    -manufacturer: "Test1"
    -colour: "polar-silber"
    -design: "Bavaro"
    -diameter: 18
  }
  2 => DataEntity {#1724
    -manufacturer: "Test2"
    -colour: "polar-silber"
    -design: "Drive"
    -diameter: 17
  }

I have to make a comma-seperated diameter based on the common manufacturer, colour & design.

My final output should be like this:

  array:5 [
  0 => DataEntity {#1024
    -manufacturer: "Test1"
    -colour: "polar-silber"
    -design: "Bavaro"
    -diameter: "17, 18"
  }
  1 => DataEntity {#1724
    -manufacturer: "Test2"
    -colour: "polar-silber"
    -design: "Drive"
    -diameter: "17"
  }

What I have tried so far is:

$manufacturer = $wheel->getManufacturer();
$design = $wheel->getDesign();
$colour = $wheel->getColour();

$key = $manufacturer. "_". $design. "_". $colour;

$wheelsArray[$key] = $wheel;
if (array_key_exists($key, $wheelsArray)) {

    $dia = $wheelsArray[$key]->getDiameter();
    $dia .= ', ' . $wheel->getDiameter();
    $wheelsArray[$key]->setDiameter($dia);
}

Here, what I get is diameter: “17, 17” instead of “17, 18”

Can anybody help me what mistake I have done?

Advertisement

Answer

You could loop through the array and set the manufacturer prop as the key of a new array:

https://paiza.io/projects/_ZzfxgMJjKIJIZAGSILmQA

<?php    

$de1 = new stdClass();
$de1->manufacturer = "Test1";
$de1->colour = "polar-silber";
$de1->design = "Bavaro";
$de1->diameter = 17;

$de2 = new stdClass();
$de2->manufacturer = "Test1";
$de2->colour = "polar-silber";
$de2->design = "Bavaro";
$de2->diameter = 18;

$de3 = new stdClass();
$de3->manufacturer = "Test2";
$de3->colour = "polar-silber";
$de3->design = "Drive";
$de3->diameter = 17;

$arr = [$de1,$de2,$de3];

$resArr = [];
foreach($arr as $key => $val){
    if(isset($resArr[$val->manufacturer])){
        $resArr[$val->manufacturer]->diameter .= ", ".$val->diameter;
    } else{
        $resArr[$val->manufacturer] = $val;
    }
}

print_r($resArr); 

?>

Result:

Array
(
    [Test1] => stdClass Object
        (
            [manufacturer] => Test1
            [colour] => polar-silber
            [design] => Bavaro
            [diameter] => 17, 18
        )

    [Test2] => stdClass Object
        (
            [manufacturer] => Test2
            [colour] => polar-silber
            [design] => Drive
            [diameter] => 17
        )

)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement