php 递归json的类代码

  1. <?php
  2. /*
  3. * @ anthor:QD
  4. * @ time: 2013-09-27
  5. */
  6. class json{
  7. private $Arr = array(); //传入数组
  8. //构造器
  9. public function json($array)
  10. {
  11. if(!is_array($array)) return false;
  12. $this->Arr = $array;
  13. }
  14. //解析主函数
  15. public function MainArr()
  16. {
  17. $arr = $this->Arr;
  18. if($this->TypeArr($arr))
  19. {
  20. $json = $this->NumArr($arr);
  21. }
  22. else
  23. {
  24. $json = $this->IndexArr($arr);
  25. }
  26. return $json;
  27. }
  28. //解析索引数组
  29. public function IndexArr($arr)
  30. {
  31. $str ="";
  32. foreach($arr as $k=>$value)
  33. {
  34. if(is_array($value))
  35. {
  36. if($this->TypeArr($value)) { $sun=$this->NumArr($value);}
  37. else {$sun=$this->IndexArr($value);}
  38. if(strpos($sun,"}") || strpos($sun,"]"))
  39. {
  40. $str .= """.$k."":".$sun.",";
  41. }
  42. else
  43. {
  44. $str .= """.$k."":"".$sun."",";
  45. }
  46. }
  47. else
  48. {
  49. $str .= """.$k."":"".$value."",";
  50. }
  51. }
  52. $str = "{".trim($str,",")."}";
  53. return $str;
  54. }
  55. //解析数字数组
  56. public function NumArr($arr)
  57. {
  58. $str = "";
  59. foreach($arr as $value)
  60. {
  61. if(is_array($value))
  62. {
  63. if($this->TypeArr($value)) { $sun=$this->NumArr($value);}
  64. else {$sun=$this->IndexArr($value);}
  65. if(strpos($sun,"}") || strpos($sun,"]"))
  66. {
  67. $str .= $sun.",";
  68. }
  69. else
  70. {
  71. $str .= """.$sun."",";
  72. }
  73. }
  74. else
  75. {
  76. $str .= """.$value."",";
  77. }
  78. }
  79. $str = "[".trim($str,",")."]";
  80. return $str;
  81. }
  82. //检验一个数组是不是严格数字索引
  83. public function TypeArr($arr)
  84. {
  85. if(array_values($arr) === $arr) return true;
  86. return false;
  87. }
  88. }
  89. ?>