当前位置:首页 > PHP教程 > php数组 > 列表

php数组转成json格式的方法

发布:smiling 来源: PHP粉丝网  添加日期:2021-05-15 22:36:41 浏览: 评论:0 

这篇文章主要介绍了php数组转成json格式的方法,实例分析了php操作数组及json格式数据的方法,需要的朋友可以参考下

本文实例讲述了php数组转成json格式的方法。分享给大家供大家参考。具体实现方法如下:

  1. function array_to_json( $array ){ 
  2.     if( !is_array( $array ) ){ 
  3.         return false; 
  4.     } 
  5.     $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) )); 
  6.     if( $associative ){ 
  7.         $construct = array(); 
  8.         foreach( $array as $key => $value ){ 
  9.             // We first copy each key/value pair into a staging array, 
  10.             // formatting each key and value properly as we go. 
  11.             // Format the key: 
  12.             if( is_numeric($key) ){ 
  13.                 $key = "key_$key"; 
  14.             } 
  15.             $key = "'".addslashes($key)."'"; 
  16.             // Format the value: 
  17.             if( is_array( $value )){ 
  18.                 $value = array_to_json( $value ); 
  19.             } else if( !is_numeric( $value ) || is_string( $value ) ){ 
  20.                 $value = "'".addslashes($value)."'"; 
  21.             } 
  22.             // Add to staging array: 
  23.             $construct[] = "$key: $value"; 
  24.         } 
  25.         // Then we collapse the staging array into the JSON form: 
  26.         $result = "{ " . implode( ", ", $construct ) . " }"; 
  27.     } else { // If the array is a vector (not associative): 
  28.         $construct = array(); 
  29.         foreach( $array as $value ){ 
  30.             // Format the value: 
  31.             if( is_array( $value )){ 
  32.                 $value = array_to_json( $value ); 
  33.             } else if( !is_numeric( $value ) || is_string( $value ) ){ 
  34.                 $value = "'".addslashes($value)."'"; 
  35.             } 
  36.             // Add to staging array: 
  37.             $construct[] = $value; 
  38.         } 
  39.         // Then we collapse the staging array into the JSON form: 
  40.         $result = "[ " . implode( ", ", $construct ) . " ]"; 
  41.     } 
  42.     return $result; 
  43. } 

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

Tags: php数组转成json

分享到: