-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
            )
    )
)
2
  • 3
    foreach ($data as $array) { $output[$array['category']][] = $array; } print_r($output); should do the trick. Commented Dec 15, 2015 at 8:39
  • 2
    It would be preferable if you use var_export() rather than var_dump() to output your arrays, because people then can reuse the output for their code examples. Commented Dec 15, 2015 at 8:48

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

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.