如何通过 php 中的 foreach 循环传递 JSON 数据

问题描述 投票:0回答:1

我希望 JSON 数据在 php 中考虑 foreach 循环,但每次我尝试这样做时都会收到此错误消息:

可捕获的致命错误:无法转换类 stdClass 的对象 串起来

PHP:

<?php
  $xml_events = simplexml_load_file('xml_data/current_events.xml');

  $results = array();


  foreach ($xml_events->event as $event) {
    array_push($results, array(
        'name' => $event->name,
        'cover' => $event->cover,
    ));
  }

  $data = json_encode($results);
  $json = json_decode($data);

  foreach ($json as $name)
  {
    echo $name->name; 
  }

XML:

<?xml version="1.0"?>
<data>
  <event>
    <name>Barclays ATP World Tour Finals</name>
  </event>
</data>

JSON 数据:

"[{"name":{"0":"Barclays ATP World Tour Finals"}},{"name":{"0":"2015 National Television Awards"}},{"name":{"0":"Barclays ATP World Tour Finals"}},{"name":{"0":"Barclays ATP World Tour Finals"}},{"name":{"0":"Barclays ATP World Tour Finals"}},{"name":{"0":"Doctor who"}},{"name":{"0":"Apple Party"}},{"name":{"0":"ice-cream"}}]"
php arrays json xml foreach
1个回答
0
投票

$name 是一个对象,所以解决方案是使用:

echo $name->name->{0};
© www.soinside.com 2019 - 2024. All rights reserved.