group duplicate values from array and print them php

  arrays, php

I have list with categories that sometimes appear duplicate. I want to them belonging to the same category as in groups. Current output is as follows:

Mercedes
Vito

Mercedes
A Klasse

Opel
Corsa

Mercedes
CLA

I want them to print like:

Mercedes
Vito
A Klasse
CLA

Opel
Corsa

my code:

$string = json_decode('{"cars_array":[{"brand":"Mercedes","model":"Vito"},{"brand":"Mercedes","model":"A Klasse"},{"brand":"Opel","model":"Corsa"},{"brand":"Mercedes","model":"CLA"}]}',true);
$catArray = array();

foreach ($string['cars_array'] as $k => $product) {
    echo $product['brand']."n";
    echo $product['model']."nn";
}

What I have tried so far:

$string = json_decode('{"cars_array":[{"brand":"Mercedes","model":"Vito"},{"brand":"Mercedes","model":"A Klasse"},{"brand":"Opel","model":"Corsa"},{"brand":"Mercedes","model":"CLA"}]}',true);
$catArray = array();

foreach ($string['cars_array'] as $k => $product) {

    if (array_key_exists($product['brand'], $catArray)) {
        $catArray[$product['brand']] = array('model' => $product['model'] );
    }else{
        $catArray[$product['brand']] = $product['brand'];
        $catArray[$product['brand']] = array('model' => $product['model'] );
    }
   
}

var_dump($catArray);

Source: Ask PHP

LEAVE A COMMENT