1

我正在尝试在 PHP 中使用 JSON,我想知道当从 json_decode 返回信息时,是否有人可以帮助我访问 $events=>$url。什么是可变路径。返回数据中有许多循环记录,我正在使用类似的东西:

$data = json_decode($feeds,true);
    foreach($data as $item=>$events) {
                    $date = $events=>$month.'/'.$events=>$day.'/'.$events=>$year;
                    $events.='<li><span class="engindate">'.$date.'</span><br /><span class="source">'.$item["title"].'</span><br /><a href="'.$item["url"].'">'.$item["details"].'</a></li>';  
                }

这是 JSON 示例(是的,我知道它不完整)

{
  "month": 5,
  "year": 2013,
  "events": [
    {
      "url": "http://www.engin.umich.edu/college/about/cal/events/2013/may/shavuot-ends",
      "id": "shavuot-ends",
      "month": 5,
      "year": 2013,
      "day": 16,
      "startTime": "1:42",
      "endTime": "1:42",
      "hideTime": "true",
      "deadline": "true",
      "am_pm": "pm",
      "am_pm_start": "pm",
      "am_pm_end": "pm",
      "title": "Shavuot ends",
      "location": "",
      "details": "Shavuot runs from May 14 to May 16.",
      "host": "Michigan Engineering",
      "event_type": "Holiday",
      "image": {
        "src": "http://www.engin.umich.edu/++resource++umich_images/default_event.jpg",
        "alt": "Shavuot ends"
      }
    },...
4

3 回答 3

1

$data['events']['url']

数组是多维的。

foreach($data as $key=>$item) {
    if($key=='events') {
        $url = $item['url'];
    }
}

或者

foreach($data['events'] as $key=>$item) {
    if($key=='url') {
        $url = $item;
    }
}
于 2013-05-16T15:45:09.440 回答
1

你把你的->=>运营商搞混了。试试这样:

$data = json_decode($feeds,true);
    foreach($data['events'] as $event) {
                    $date = $event['month'].'/'.$event['day'].'/'.$event['year'];
                    $events.='<li><span class="engindate">'.$date.'</span><br /><span class="source">'.$event["title"].'</span><br /><a href="'.$event["url"].'">'.$event["details"].'</a></li>';  
                }
于 2013-05-16T15:46:53.697 回答
0

尝试这个:

$data = json_decode($feeds);

$eventsHtml = "";
foreach($data->events as $event ) {
                    $date = $data->month.'/'.$event->day.'/'.$data=>year;
                    $eventsHtml .='<li><span class="engindate">'.$date.
                                  '</span><br /><span class="source">'.
                                   $event=>title.
                                   '</span><br /><a href="'.$event=>url.'">'.
                                   $event->details.'</a></li>';  
                }

你有一个对象“ data”。这有一个成员“ month”,所以这是$data->month 它有一个成员“ events”,它是一个数组。第一个事件是$data->events[0]。如果您使用 a 进行迭代,foreach则这是一个事件。foreach($data->events as $event ) {$event

基本错误:

$events=>$month // is inproper syntax
foreach($data as $item=>$events) {
        ..
        $events.= // this would overwrite the iterator variable above ??
于 2013-05-16T15:53:26.833 回答