如何操纵php数组

时间:2015-12-15 08:34:59

标签: php

如何操作php数组。我在下面有一个$ data变量。

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

现在我想将数据分组,如下所示。 。我对php并不熟悉。有人可以帮助我如何实现这一目标。我应该使用什么功能。感谢

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 个答案:

答案 0 :(得分:3)

迭代数组并根据category字段的内容将其添加到新数组中:

$new = array();
foreach ($data as $val) {
    $new[$val['category']][] = $val;
}

答案 1 :(得分:1)

这可以满足您的要求

<?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>";

这是一个有效的演示 - http://codepad.viper-7.com/G4Br28