PHP JSON to array

WBOY
Release: 2016-07-25 09:10:31
Original
1256 people have browsed it
  1. $s='{"webname":"homehf","url":"www.homehf.com","qq":"744348666"}';

  2. $web=json_decode($s); //Convert characters to JSON
  3. $arr=array();
  4. foreach($web as $k=>$w) $arr[$k]=$w;< ;/p>
  5. The first three lines can be replaced by $web=json_decode($s,true);

  6. print_r($arr);

  7. ?>
Copy code

In the above code, a JSON object has been converted into an array, but if it is a nested JSON, the above code is obviously useless, so we write a function to solve the nested JSON ,

  1. function json_to_array($web){

  2. $arr=array();
  3. foreach($web as $k=>$w){
  4. if(is_object ($w)) $arr[$k]=json_to_array($w); //Judge whether the type is object
  5. else $arr[$k]=$w;
  6. }
  7. return $arr;
  8. }
  9. $s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf @163.com","xx":"xxxxxxx"}}';

  10. $web=json_decode($s);
  11. $arr=json_to_array($web);

  12. //Up One line can be replaced by $web=json_decode($s,true);

  13. print_r($arr);
  14. ?>

Copy code

The custom json_to_array() method can convert any Convert nested JSON to array.



Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template