0

How can I show this array in a grouped way according to the value "cat"?

My array:

$options = array(
    array("cat" => "Impresoras","nameProd" => "Impresora 4"),
    array("cat" => "Destructoras","nameProd" => "Destructora 3"),
    array("cat" => "Impresoras","nameProd" => "Impresora 8"),
    array("cat" => "Destructoras","nameProd" => "Destructora 5")
);

I need to print:

Impresoras: Impresora 4, Impresora 8
Destructoras: Destructora 3, Destructora 5
1

3 Answers 3

1

Try this

  $options  = array(
    array("cat" => "Impresoras","nameProd" => "Impresora 4"),
    array("cat" => "Destructoras","nameProd" => "Destructora 3"),
    array("cat" => "Impresoras","nameProd" => "Impresora 8"),
    array("cat" => "Destructoras","nameProd" => "Destructora 5")
  );

  foreach ($options as $key => $value) {    
    $nArray[$value['cat']][] =  $value['nameProd'];      
  }
  foreach ($nArray as $key => $value) {
    echo $key.":".implode(",", $value)."<br>";
  }

Output

Impresoras:Impresora 4,Impresora 8
Destructoras:Destructora 3,Destructora 5
Sign up to request clarification or add additional context in comments.

1 Comment

Output: Impresoras:Impresora 4,Impresora 8 Destructoras:Destructora 3,Destructora 5 Impresoras:Impresora 4,Impresora 8,Impresora 4,Impresora 8 Destructoras:Destructora 3,Destructora 5,Destructora 3,Destructora 5 Impresoras:Impresora 4,Impresora 8,Impresora 4,Impresora 8,Impresora 4,Impresora 8 Destructoras:Destructora 3,Destructora 5,Destructora 3,Destructora 5,Destructora 3,Destructora 5
1

Create a new array with the cat as key. Someting like this;

$grouped_categories = array();
foreach ( $options as $option ) {
    $grouped_categories[$option['cat']][] = $option['nameProd'];
}

This will output something like;

[
    'Impresoras' => ['Impresora 4', 'Impresora 8']
    'Destructoras' => [...]
]

How you want to output that array is up to you.

1 Comment

Output:Impresora 4 Destructora 3 Impresora 8 Destructora 5 Impresora 4 Destructora 3 Impresora 8 Destructora 5 Impresora 4 Destructora 3 Impresora 8 Destructora 5
0
    $data = [];
    $options = array(
        array("cat" => "Impresoras", "nameProd" => "Impresora 4"),
        array("cat" => "Destructoras", "nameProd" => "Destructora 3"),
        array("cat" => "Impresoras", "nameProd" => "Impresora 8"),
        array("cat" => "Destructoras", "nameProd" => "Destructora 5")
    );

    foreach ($options as $key => $value) {
        $data[$value['cat']][] = $value['nameProd'];
    };

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.