Home > Software engineering >  group duplicate values from array and print them php
group duplicate values from array and print them php

Time:11-25

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']."\n\n";
}

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);

CodePudding user response:

You can group items by using a named array, then assign values by pushing them with [] syntax


$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) {

    // create an array grouped on brand’s value
    $catArray[$product['brand']][] = $product['model'];

    echo $product['brand']."\n";
    echo $product['model']."\n\n";
}

foreach($catArray as $brand => $modelList) {
    print "$brand\n";
    foreach($modelList as $model) {
        print "$model\n";
    }
    print "\n";
}
        

CodePudding user response:

try to use array unique in $string

$string_arr = array_unique($string);
  • Related