Home  >  Article  >  Backend Development  >  php convert index array to json

php convert index array to json

*文
*文Original
2017-12-27 11:31:431838browse

本文主要介绍了php实现数组中索引关联数据转换成json对象的方法,基于Yii框架分析了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解决JSON中文显示问题

详解php json相关函数的用法示例

php json与xml序列化/反序列化

The above is the detailed content of php convert index array to json. For more information, please follow other related articles on the PHP Chinese website!

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