php多维数组排序与操作函数
PHP多维数组排序与操作函数,代码如下:
- function arraycd($arr){
- static $res_arr=array();
- if(is_array($arr))
- {
- foreach($arr as $key=>$val)
- {
- if(is_array($val))
- {
- arraycd($val);
- }else{
- $res_arr[]=$val;
- }
- }
- }elseif(is_string($arr))
- {
- $res_arr[]=$arr;
- }
- return implode(",",$res_arr);
- }
- $fruits = array (
- "fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
- "numbers" => array(1, 2, 3, 4, 5, 6),
- "holes" => array("first", 5 => "second", "third")
- );
- $strayy=arraycd($fruits);
- var_dump($strayy);
看一个多维数组排序,代码如下:
- function sortdata($data, $col, $order){
- if (count($data)) $temp_array[key($data)] = array_shift($data);
- foreach($data as $key => $val){
- $offset = 0;
- $found = false;
- foreach($temp_array as $tmp_key => $tmp_val){
- if(!$found and strtolower($val[$col]) >
- strtolower($tmp_val[$col])){
- $temp_array = array_merge((array)
- array_slice($temp_array,0,$offset),
- array($key => $val),
- array_slice($temp_array,$offset)
- );
- $found = true;
- }
- $offset++;
- }
- if(!$found) {
- $temp_array = array_merge($temp_array, array
- ($key => $val));
- }
- }
- if (strtolower($order)=="asc"){
- $array = array_reverse($temp_array);
- } else {
- $array = $temp_array;
- }
- return $array;
- }
- 主函数
- $data=array(
- array(
- 'name'=>'alice',
- 'key'=>'2fc4ab3d639e5400efdfc73bc27e83f1',
- 'age'=>20
- ),
- array(
- 'name'=>'claudia',
- 'key'=>'831c2b79c1f19af39c7e3321e11e5f5e',
- 'age'=>18
- ),
- array(
- 'name'=>'beatrice',
- 'key'=>'6f8512a2066b8f35a27a495ce1228c76',
- 'age'=>100
- ),
- array(
- 'name'=>'denise',
- 'age'=>25,
- 'key'=>'ef6de3b178bf9f69a9fef72e4ee7bbe9'
- )
- );
- $arr1 = sortdata($data, "name","asc");
- echo "<pre>";
- var_dump($arr1);
- echo "</pre>";
- $arr2 = sortdata($data, "age","desc");
- echo "<pre>";
- var_dump($arr2);
- echo "</pre>";