Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2017
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. <?php
  2. function array_string($arr,$opts='php') {
  3.  
  4. if (is_array($opts)) $opts['depth']++;
  5. else {
  6. if (!is_string($opts)) {
  7. $in = $opts;
  8. $opts = is_integer($in) ? "json" : 'php';
  9. if ($in) $opts .= " pretty print";
  10.  
  11. }
  12. $args = preg_split('/[^a-z0-9]/i', $opts);
  13. if (in_array('json', $args))
  14. $opts = array('open'=>'{','close'=>'}','sep'=>': ', 'integers'=>false);
  15. else $opts = array('open'=>'[','close'=>']','sep'=>' => ','integers'=>true);
  16. if (!in_array('pretty', $args)) $opts = $opts + array('indent'=>'','eol'=>'');
  17. else $opts = $opts + array('indent'=>' ','eol'=>"\n" );
  18. $opts['depth'] = 1; #starts at 1
  19. $opts['print'] = in_array('print', $args) || in_array('echo', $args) ? true:false;
  20. }
  21. end($arr); $last = key($arr);
  22. $result = "$opts[open]$opts[eol]";
  23.  
  24. foreach($arr as $k=>$v){
  25. $result .= str_repeat($opts['indent'],$opts['depth']);
  26. if (!$opts['integers']) $result .= "\"$k\"$opts[sep]";
  27. else $result .= is_integer($k) ? " $k$opts[sep]" : "\"$k\"$opts[sep]";
  28. if (is_array($v)) $result .= array_string($v,$opts);
  29. elseif(is_bool($v)) $result .= $v ? "true":"false";
  30. elseif(is_numeric($v)) $result .= $v;
  31. else $result .= "\"".addslashes($v)."\"";
  32. $result .= $last===$k ? $opts['eol'] : ", $opts[eol]";
  33. }
  34. $opts['depth']--;
  35. $result .= str_repeat($opts['indent'],$opts['depth']).$opts['close'];
  36. if ($opts['depth']===0) {
  37. $result .= $opts['eol'];
  38. if ($opts['print']) echo $result;
  39. }
  40. return $result;
  41. }
  42.  
  43. $arr = array(
  44. "one"=>true,
  45. "two",
  46. "subarray"=>array(
  47. array(
  48. "string"=>"yo",
  49. "float"=>1234.0000
  50. ),
  51. array(
  52. 'a string',
  53. "time"=>6.022e23
  54. )
  55. )
  56. );
  57. array_string($arr, 'json print');
  58. array_string($arr, 'json pretty print');
  59.  
  60. echo "no output...\n";
  61. array_string($arr, 'json pretty');
  62. array_string($arr, 'json');
  63. array_string($arr, 'php pretty');
  64. array_string($arr, 'php');
  65. echo "end no output...\n";
  66.  
  67. array_string($arr, 'php print');
  68. array_string($arr, 'php print print');
  69.  
  70. echo "no output...\n";
  71. array_string($arr, 'php pretty');
  72. array_string($arr, 'php');
  73. array_string($arr, 'php pretty');
  74. array_string($arr, 'php');
  75. echo "end no output...\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement