## 数组处理目录
[TOC=2,3]
* * * * *
* * * * *
* * * * *
- ## 根据相同值再分组
* * * * *
>[info]#### 1. 根据相同值再分组
~~~
原数组
$arr = array(
0 => array(
'initial' => 'A',
'typename' => '奥迪'
),
1 => array(
'initial' => 'F',
'typename' => 'F1'
),
2 => array(
'initial' => 'F',
'typename' => 'F2'
)
);
~~~
>[info]#### 2. 测试
- #### 使用
~~~
$result = array();
foreach ($arr as $k => $v) {
$result[$v['initial']][] = $v;
}
echo "<pre>";
var_dump($result);
echo "</pre>";
~~~
- #### 结果
~~~
array(2) {
["A"]=>array(1) {
[0]=>array(2) {
["initial"]=>string(1) "A"
["typename"]=> string(6) "奥迪"
}
}
["F"]=> array(2) {
[0]=>array(2) {
["initial"]=>string(1) "F"
["typename"]=>string(2) "F1"
}
[1]=>array(2) {
["initial"]=>string(1) "F"
["typename"]=> string(2) "F2"
}
}
}
~~~
* * * * *
* * * * *
* * * * *
- ## 根据某列对二维数组进行排序
* * * * *
>[info]#### 1. 根据某列对二维数组进行排序【array_sort】
~~~
/**
* 根据某列对二维数组进行排序
* @param unknown $arr
* @param unknown $row
* @param string $type
* @return multitype:unknown
*/
function array_sort($arr,$row,$type="asc"){
//定义一个临时数组
$arr_temp=array();
foreach ($arr as $v){
$arr_temp[$v[$row]]=$v;//遍历取出每个二维数组某列的值,重新构造以某列排序的临时数组
}
if ($type=="asc") {
ksort($arr_temp);
}else {
krsort($arr_temp);
}
return $arr_temp;
}
~~~
>[info]#### 2. 测试
- #### 函数使用
~~~
$person=array(
array('id'=>2,'name'=>'zhangsan','age'=>20),
array('id'=>4,'name'=>'lisi','age'=>22),
array('id'=>3,'name'=>'wangwu','age'=>24),
);
$person=array_sort($person,'age','desc');
echo "<pre>";
print_r($person);
echo "<pre/>";
~~~
- #### 函数结果
~~~
Array
(
[24] => Array
(
[id] => 3
[name] => wangwu
[age] => 24
)
[22] => Array
(
[id] => 4
[name] => lisi
[age] => 22
)
[20] => Array
(
[id] => 2
[name] => zhangsan
[age] => 20
)
~~~