PHP实现数组转JSon和JSon转数组的方法示例

这篇文章主要介绍了PHP实现数组转JSon和JSon转数组的方法,结合实例形式分析了php数组与json相互转换实现方法与操作技巧,需要的朋友可以参考下。

本文实例讲述了PHP实现数组转JSon和JSon转数组的方法,分享给大家供大家参考,具体如下:

数组转JSon数据:

  1. $array_1 = array(); //一维数组
  2. $array_2 = array(); //多维数组
  3. $array_1['username']='ericwolf';
  4. $array_1['age']=25;
  5. $array_2['menber']['aa']['username']='ericwolf';
  6. $array_2['menber']['aa']['age']=25;
  7. $array_2['menber']['bb']['username']='eeee';
  8. $array_2['menber']['bb']['age']=22;
  9. print_r($array_2);
  10. $jsonObj_1 = json_encode($array_1);
  11. var_dump($jsonObj_1);
  12. $jsonObj_1 = json_encode($array_2);
  13. var_dump($jsonObj_1);

运行结果:

  1. Array
  2. (
  3. [menber] => Array
  4. (
  5. [aa] => Array
  6. (
  7. [username] => ericwolf
  8. [age] => 25
  9. )
  10. [bb] => Array
  11. (
  12. [username] => eeee
  13. [age] => 22
  14. )
  15. )
  16. )
  17. string(32) "{"username":"ericwolf","age":25}"
  18. string(84) "{"menber":{"aa":{"username":"ericwolf","age":25},"bb":{"username":"eeee","age":22}}}"

JSon转数组,并打印:

  1. $jsonStr = '{"key":"value","key1":"value1"}';
  2. $json2Array = json_decode($jsonStr,true);
  3. foreach($json2Array as $key=>$val) {
  4. echo $key."=".$val."<br/>";
  5. }

运行结果:

key=value

key1=value1