PHP / JSON – stdClass对象

前端之家收集整理的这篇文章主要介绍了PHP / JSON – stdClass对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我还不清楚数组.我需要一些帮助 – 我有一些 JSON,我已经通过一些基本上解析JSON并且解码它的 PHP来运行它,如下所示:
  1. stdClass Object
  2. (
  3. [2010091907] => stdClass Object
  4. (
  5. [home] => stdClass Object
  6. (
  7. [score] => stdClass Object
  8. (
  9. [1] => 7
  10. [2] => 17
  11. [3] => 10
  12. [4] => 7
  13. [5] => 0
  14. [T] => 41
  15. )
  16.  
  17. [abbr] => ATL
  18. [to] => 2
  19. )

这实际上是继续的 – 但是 – 我的问题是stdClass对象部分.我需要能够在for循环中调用它,然后遍历每个部分(home,score,abbr,to等).我该怎么办?

您可以使用get_object_vars()获取对象属性的数组,或者使用json_decode($string,true)调用json_decode();获取关联数组.

例:

  1. <?PHP
  2. $foo = array('123456' =>
  3. array('bar' =>
  4. array('foo'=>1,'bar'=>2)));
  5.  
  6.  
  7. //as object
  8. var_dump($opt1 = json_decode(json_encode($foo)));
  9.  
  10. echo $opt1->{'123456'}->bar->foo;
  11.  
  12. foreach(get_object_vars($opt1->{'123456'}->bar) as $key => $value){
  13. echo $key.':'.$value.PHP_EOL;
  14. }
  15.  
  16. //as array
  17. var_dump($opt2 = json_decode(json_encode($foo),true));
  18.  
  19. echo $opt2['123456']['bar']['foo'];
  20.  
  21. foreach($opt2['123456']['bar'] as $key => $value){
  22. echo $key.':'.$value.PHP_EOL;
  23. }
  24. ?>

输出

  1. object(stdClass)#1 (1) {
  2. ["123456"]=>
  3. object(stdClass)#2 (1) {
  4. ["bar"]=>
  5. object(stdClass)#3 (2) {
  6. ["foo"]=>
  7. int(1)
  8. ["bar"]=>
  9. int(2)
  10. }
  11. }
  12. }
  13. 1
  14. foo:1
  15. bar:2
  16.  
  17. array(1) {
  18. [123456]=>
  19. array(1) {
  20. ["bar"]=>
  21. array(2) {
  22. ["foo"]=>
  23. int(1)
  24. ["bar"]=>
  25. int(2)
  26. }
  27. }
  28. }
  29. 1
  30. foo:1
  31. bar:2

猜你在找的PHP相关文章