-1

How to manipulate php arrays. I have a $data variable below.

$data = Array
(
 [0] => Array
    (
        [id] => 1
        [capacity] => 900
        [category] => users
    )

 [1] => Array
    (
        [id] => 2
        [capacity] => 300
        [category] => users
    )
 [2] => Array
    (
        [id] => 3
        [capacity] => 900
        [category] => students
    )
 [3] => Array
    (
        [id] => 4
        [capacity] => 300
        [category] => students
    )
)

Now I want to group the data with same category like below. . I am not really familiar in php. Can somebody out there help me how to achieve this. What function should I used. Thanks

Array
(
[users] => Array
    (
        [0] => Array
            (
              [id] => 1
              [capacity] => 900
              [category] => users
            )

        [1] => Array
            (
              [id] => 2
              [capacity] => 300
              [category] => users
            )
    ),
[students] => Array
    (
        [0] => Array
            (
              [id] => 1
              [capacity] => 900
              [category] => students
            )

        [1] => Array
            (
              [id] => 2
              [capacity] => 300
              [category] => students
            )
    )
)
qazzu
  • 361
  • 3
  • 5
  • 16
  • 3
    `foreach ($data as $array) { $output[$array['category']][] = $array; } print_r($output);` should do the trick. – scrowler Dec 15 '15 at 08:39
  • 2
    It would be preferable if you use [var_export()](http://php.net/manual/en/function.var-export.php) rather than [var_dump()](http://php.net/manual/en/function.var-dump.php) to output your arrays, because people then can reuse the output for their code examples. – syck Dec 15 '15 at 08:48

2 Answers2

3

Just iterate over the array and add it depending on the content of the category field to a new array:

$new = array();
foreach ($data as $val) {
    $new[$val['category']][] = $val;
}
syck
  • 2,984
  • 1
  • 13
  • 23
1

This does what you requested

<?php

$data = array(
    0 => array (
        "id" => 1,
        "capacity" => 900,
        "category" => "users"
    ),
    1 => array (
        "id" => 2,
        "capacity" => 300,
        "category" => "users"
    ),
    2 => array (
        "id" => 3,
        "capacity" => 900,
        "category" => "students"
    ),
    3 => array (
        "id" => 4,
        "capacity" => 300,
        "category" => "students"
    )
);

$groups = array();

foreach ($data as $i) {
  if ($i['category'] === "students") {
    $groups['students'][] = $i;
  }
  else if ($i['category'] === "users") {
    $groups['users'][] = $i;
  }
}

echo "<pre>", print_r($groups), "</pre>";

Here is a working demo - http://codepad.viper-7.com/G4Br28

the_velour_fog
  • 2,094
  • 4
  • 17
  • 29