php多维数组排序与操作函数

PHP多维数组排序与操作函数,代码如下:

  1. function arraycd($arr){
  2. static $res_arr=array();
  3. if(is_array($arr))
  4. {
  5. foreach($arr as $key=>$val)
  6. {
  7. if(is_array($val))
  8. {
  9. arraycd($val);
  10. }else{
  11. $res_arr[]=$val;
  12. }
  13. }
  14. }elseif(is_string($arr))
  15. {
  16. $res_arr[]=$arr;
  17. }
  18. return implode(",",$res_arr);
  19. }
  20. $fruits = array (
  21. "fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
  22. "numbers" => array(1, 2, 3, 4, 5, 6),
  23. "holes" => array("first", 5 => "second", "third")
  24. );
  25. $strayy=arraycd($fruits);
  26. var_dump($strayy);

看一个多维数组排序,代码如下:

  1. function sortdata($data, $col, $order){
  2. if (count($data)) $temp_array[key($data)] = array_shift($data);
  3. foreach($data as $key => $val){
  4. $offset = 0;
  5. $found = false;
  6. foreach($temp_array as $tmp_key => $tmp_val){
  7. if(!$found and strtolower($val[$col]) >
  8. strtolower($tmp_val[$col])){
  9. $temp_array = array_merge((array)
  10. array_slice($temp_array,0,$offset),
  11. array($key => $val),
  12. array_slice($temp_array,$offset)
  13. );
  14. $found = true;
  15. }
  16. $offset++;
  17. }
  18. if(!$found) {
  19. $temp_array = array_merge($temp_array, array
  20. ($key => $val));
  21. }
  22. }
  23. if (strtolower($order)=="asc"){
  24. $array = array_reverse($temp_array);
  25. } else {
  26. $array = $temp_array;
  27. }
  28. return $array;
  29. }
  30. 主函数
  31. $data=array(
  32. array(
  33. 'name'=>'alice',
  34. 'key'=>'2fc4ab3d639e5400efdfc73bc27e83f1',
  35. 'age'=>20
  36. ),
  37. array(
  38. 'name'=>'claudia',
  39. 'key'=>'831c2b79c1f19af39c7e3321e11e5f5e',
  40. 'age'=>18
  41. ),
  42. array(
  43. 'name'=>'beatrice',
  44. 'key'=>'6f8512a2066b8f35a27a495ce1228c76',
  45. 'age'=>100
  46. ),
  47. array(
  48. 'name'=>'denise',
  49. 'age'=>25,
  50. 'key'=>'ef6de3b178bf9f69a9fef72e4ee7bbe9'
  51. )
  52. );
  53. $arr1 = sortdata($data, "name","asc");
  54. echo "<pre>";
  55. var_dump($arr1);
  56. echo "</pre>";
  57. $arr2 = sortdata($data, "age","desc");
  58. echo "<pre>";
  59. var_dump($arr2);
  60. echo "</pre>";