La función array2json(), JSON para todos.
PHP en sus últimas versiones cuenta con una extención para converir arreglos asociativos o indexados en literales JSON y viceversa. Encontré en bin-co la función array2json() que nos ayuda a realizar la misma operación como si tuvieramos instalada la extención. La verdad tuve que hacerle una pequeña modificación, ya que cuando el arreglo solo tenia un ítem devolvia una lista en vez de un objeto.
Arreglo de PHP:
$data = array(
'success' => "Sweet",
'failure' => false,
'array' => array(),
'numbers' => array(1,2,3),
'info' => array(
'name' => 'Binny',
'site' => 'http://www.openjs.com/'
)
);
Implementando la función:
$json = array2json($data);
El resultado es esta cadena:
{"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}}
Y esta es la función:
function array2json($arr) {
if(function_exists('json_encode')) return json_encode($arr); //Lastest versions of PHP already has this functionality.
$parts = array();
$is_list = false;
//Find out if the given array is a numerical array
$keys = array_keys($arr);
$max_length = count($arr)-1;
if(($keys[0] == 0) and ($keys[$max_length] == $max_length) and $maxlength) {//See if the first key is 0 and last key is length - 1
$is_list = true;
for($i=0; $i$value) {
if(is_array($value)) { //Custom handling for arrays
if($is_list) $parts[] = array2json($value); /* :RECURSION: */
else $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */
} else {
$str = '';
if(!$is_list) $str = '"' . $key . '":';
//Custom handling for multiple data types
if(is_numeric($value)) $str .= $value; //Numbers
elseif($value === false) $str .= 'false'; //The booleans
elseif($value === true) $str .= 'true';
else $str .= '"' . addslashes($value) . '"'; //All other things
// :TODO: Is there any more datatype we should be in the lookout for? (Object?)
$parts[] = $str;
}
}
$json = implode(',',$parts);
if($is_list) return '[' . $json . ']';//Return numerical JSON
return '{' . $json . '}';//Return associative JSON
}
Una muy buena solución. I love Javascript.
Todavía no hay comentarios
Replica

