Skip to content

Instantly share code, notes, and snippets.

@tarranjones
Created November 12, 2015 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tarranjones/644a3a40809ef33fcb5b to your computer and use it in GitHub Desktop.
Save tarranjones/644a3a40809ef33fcb5b to your computer and use it in GitHub Desktop.
<php
class helper {
//is_array & is associative array
public function is_array_asso($a) {
return $this->is_asso($a, 1);
}
// is associative array
public function is_asso($a, $strict = FALSE) {
if($strict && !is_array($a)){
return false;
}
foreach(array_keys($a) as $key){
if (is_string($key)) {
return true;
}
}
return false;
}
// Object to array (visibility and namespace removal)
public function obj_to_array($d){
$array = array();
if (is_object($d)) {
foreach ((array)$d as $k => $v) {
$k = preg_match('/^\x00(?:.*?)\x00(.+)/', $k, $matches) ? $matches[1] : $k;
$array[$k] = $this->obj_to_array($v);
}
return $array;
} else if (is_array($d)) {
foreach ($d as $k => $v) {
$array[$k] = $this->obj_to_array($v);
}
return $array;
}
return $d;
}
public function autofix_json_encode($array){
if(is_object($array)){
$array = $this->obj_to_array($array);
}
$json = json_encode($array);
switch (json_last_error()) {
case JSON_ERROR_NONE:
return $json;
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
return $this->autofix_json_encode($this->utf8ize($array));
break;
default:
echo ' - Unknown error';
break;
}
return $json;
}
public function autofix_json_decode($json, $assoc = false, $depth = 512 , $options = 0 )
{
$array = json_decode($json, $assoc, $depth , $options);
switch (json_last_error()) {
case JSON_ERROR_NONE:
return $array;
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
return $this->autofix_json_decode(str_replace('\\', '\\\\', $json), $assoc, $depth , $options);
break;
case JSON_ERROR_UTF8:
return $this->autofix_json_decode($this->utf8ize($json), $assoc, $depth , $options);
break;
default:
echo ' - Unknown error';
break;
}
return $array;
}
public function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[utf8_encode($k)] = $this->utf8ize($v);
}
} elseif (is_object($d)) {
foreach ($d as $k => $v) {
$d->{utf8_encode($k)} = $this->utf8ize($v);
}
} else {
return utf8_encode($d);
}
return $d;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment