从json字符串中获取信息

时间:2013-05-16 15:43:11

标签: php json

我正在尝试使用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"
      }
    },...

3 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分: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>';  
                }

答案 2 :(得分: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]。如果您使用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 ??