为了根据key给二维数组分组,我们可以使用PHP的array_reduce()函数。
具体步骤如下:
1.定义一个空数组,用于存储结果;
2.使用array_reduce()函数遍历二维数组;
3.判断当前数组元素key值是否存在于结果数组中,如果存在,则将该元素push进对应的子数组;如果不存在,则创建该key对应的子数组并push元素进去;
4.最终返回结果数组。
以下是示例代码:
$arr = array(
array('name' => 'John', 'age' => 21, 'gender' => 'male'),
array('name' => 'Jane', 'age' => 25, 'gender' => 'female'),
array('name' => 'Bob', 'age' => 22, 'gender' => 'male'),
array('name' => 'Alice', 'age' => 27, 'gender' => 'female'),
array('name' => 'Mark', 'age' => 23, 'gender' => 'male'),
array('name' => 'Lisa', 'age' => 28, 'gender' => 'female')
);
$res = array_reduce($arr, function($carry, $item){
$key = $item['gender'];
isset($carry[$key]) ? array_push($carry[$key], $item) : $carry[$key] = array($item);
return $carry;
}, array());
print_r($res);
以上代码将根据gender键值,将原始数组分组为两个子数组,其中一个包含所有female的元素,另一个包含所有male的元素。输出结果为:
Array
(
[male] => Array
(
[0] => Array
(
[name] => John
[age] => 21
[gender] => male
)
[1] => Array
(
[name] => Bob
[age] => 22
[gender] => male
)
[2] => Array
(
[name] => Mark
[age] => 23
[gender] => male
)
)
[female] => Array
(
[0] => Array
(
[name] => Jane
[age] => 25
[gender] => female
)
[1] => Array
(
[name] => Alice
[age] => 27
[gender] => female
)
[2] => Array
(
[name] => Lisa
[age] => 28
[gender] => female
)
)
)
以下是另一个示例,它根据age键值将数组分为3个子数组,分别存储小于20岁的人、20岁到25岁的人、以及25岁以上的人:
$arr = array(
array('name' => 'John', 'age' => 21, 'gender' => 'male'),
array('name' => 'Jane', 'age' => 25, 'gender' => 'female'),
array('name' => 'Bob', 'age' => 22, 'gender' => 'male'),
array('name' => 'Alice', 'age' => 27, 'gender' => 'female'),
array('name' => 'Mark', 'age' => 23, 'gender' => 'male'),
array('name' => 'Lisa', 'age' => 28, 'gender' => 'female'),
array('name' => 'Tom', 'age' => 18, 'gender' => 'male'),
array('name' => 'Lucy', 'age' => 19, 'gender' => 'female'),
array('name' => 'Jack', 'age' => 30, 'gender' => 'male')
);
$res = array_reduce($arr, function($carry, $item){
$key = $item['age'] < 20 ? 'young' : ($item['age'] < 25 ? 'middle' : 'old');
isset($carry[$key]) ? array_push($carry[$key], $item) : $carry[$key] = array($item);
return $carry;
}, array());
print_r($res);
以上代码将根据age键值,将原始数组分为3个子数组,其中一个包含所有小于20岁的元素,另一个包含所有20岁到25岁的元素,第三个包含所有25岁以上的元素。输出结果为:
Array
(
[middle] => Array
(
[0] => Array
(
[name] => John
[age] => 21
[gender] => male
)
[1] => Array
(
[name] => Bob
[age] => 22
[gender] => male
)
[2] => Array
(
[name] => Mark
[age] => 23
[gender] => male
)
)
[old] => Array
(
[0] => Array
(
[name] => Alice
[age] => 27
[gender] => female
)
[1] => Array
(
[name] => Lisa
[age] => 28
[gender] => female
)
[2] => Array
(
[name] => Jack
[age] => 30
[gender] => male
)
)
[young] => Array
(
[0] => Array
(
[name] => Tom
[age] => 18
[gender] => male
)
[1] => Array
(
[name] => Lucy
[age] => 19
[gender] => female
)
)
)
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:PHP 根据key 给二维数组分组 - Python技术站