Home >Backend Development >PHP Tutorial >php实现数组中索引关联数据转换成json对象的方法_PHP

php实现数组中索引关联数据转换成json对象的方法_PHP

WBOY
WBOYOriginal
2016-05-30 08:46:56817browse

本文实例讲述了php实现数组中索引关联数据转换成json对象的方法。分享给大家供大家参考。具体实现方法如下:

public static function encode(&$var)
{
 return '{'.implode(',',self::encodeExcute($var)).'}';
}
private static function encodeExcute(&$var)
{
 $json = array();
 switch (gettype($var))
 {
  case 'array':
   foreach($var as $key=>$value)
   {
    if(is_array($value))
    {
     $json[] = '"'.$key.'":{'.implode(',',self::encodeExcute($value)).'}';
     //$json[$key] = self::encode($value);
    } elseif (is_object($value)) {
     $json[] = "\\"{$key}\\":".json_encode($value->attributes);
    } else {
     echo 'ERROR 未知类型,还未解析';
     Yii::app()->end();
    }
   }
   break;
  case 'object':
   break;
 }
 return $json;
}

希望本文所述对大家的php程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn