【问题标题】:Parsing json with a nested element使用嵌套元素解析 json
【发布时间】:2017-09-22 06:26:08
【问题描述】:

不适用于嵌套元素 输出第一级的元素,不读取带有数据的嵌套数组,因为可以获取值——id、title和location?

<?php

function removeBomUtf8($s){
  if(substr($s,0,3)==chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF'))){
        return substr($s,3);
    }else{
        return $s;
    }
}

$url = "https://denden000qwerty.000webhostapp.com/opportunities.json";
$content = file_get_contents($url);
$clean_content = removeBomUtf8($content);
$decoded = json_decode($clean_content);

while ($el_name = current($decoded)) {
 // echo 'total = ' . $el_name->total_items . 'current = ' . $el_name->current_page . 'total = ' . $el_name->total_pages . '<br>' ;
    echo ' id = ' . $el_name->data[0]->id . ' title = ' . $el_name->data.title . ' location = ' . $el_name->data.location . '<br>' ;
  next($decoded);
}
?>

【问题讨论】:

  • 你要解析什么?
  • "data":[{"id":412235,"title":"我们说英语","lat":"10.6966159","lng":"-74.8741045","url" :"gis.aiesec.org/v2/opportunities/…, Colombia","city":"Atlántico, Colombia","programmes":{"id":1,"short_name":"GV"},"applications_count":54,"is_favourited" :false,"branch":{"id":321136,"name":"@ UNIATLÃNTICO","organisation": 等等...
  • 我需要得到 - "id":412235,"title":"We Speak English" city":"Atlántico, Colombia"

标签: php json parsing


【解决方案1】:

$el_name-&gt;data[0]-&gt;id 是正确的

$el_name-&gt;data.title 不是

你看出区别了吗?

$decoded 是根(无需对其进行迭代)- 您想对data 子项进行迭代

<?php
foreach($decoded->data as $data)
{
    $id = (string)$data->id;
    $title = (string)$data->title;
    $location = (string)$data->location;


    echo sprintf('id = %s, title = %s, location = %s<br />', $id, $title, $location);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-18
    • 2015-09-28
    • 2020-12-07
    • 2015-03-14
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多