The Bill function almost worked, it just needed the is_assoc () function.
But while I sorted it out, I cleaned it a bit. It seems to me that this works very well:
<?php class JSObject { var $jsexp = 'JSEXP:'; function is_assoc($arr) { return (is_array($arr) && count(array_filter(array_keys($arr),'is_string')) == count($arr)); } function encode($properties = array()) { $is_assoc = $this->is_assoc($properties); $enc_left = $is_assoc ? '{' : '['; $enc_right = $is_assoc ? '}' : ']'; $outputArray = array(); foreach ($properties as $prop => $value) { if ((is_array($value) && !empty($value)) || (is_string($value) && strlen(trim(str_replace($this->jsexp, '', $value))) > 0) || is_int($value) || is_float($value) || is_bool($value)) { $output = (is_string($prop)) ? $prop.': ' : ''; if (is_array($value)) { $output .= $this->encode($value); } else if (is_string($value)) { $output .= (substr($value, 0, strlen($this->jsexp)) == $this->jsexp) ? substr($value, strlen($this->jsexp)) : json_encode($value); } else { $output .= json_encode($value); } $outputArray[] = $output; } } $fullOutput = implode(', ', $outputArray); return $enc_left . $fullOutput . $enc_right; } function js($str) { return $this->jsexp.$str; } }
source share