【问题标题】:PHP: String in json parsePHP:json解析中的字符串
【发布时间】:2013-12-25 22:25:27
【问题描述】:

我正在尝试解析 json。我在 foreach 循环中运行它,如果我执行以下操作,它会起作用:

$places = array('restaurant', 'store', 'etc')
    foreach ($this->placesCachingTypes as $places) {
      $places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
      $places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
    }

但是,当我执行以下操作时,即我将餐厅更改为 $places(我需要这样做,因为我有一系列不同的地方并且我想在 foreach 循环中解析所有这些地方)它不起作用.

foreach ($this->placesCachingTypes as $places) {
  $places_location_lat = $json_decoded->json[0]->$places[0]->geometry->location->lat;
  $places_location_lng = $json_decoded->json[0]->$places[0]->geometry->location->lng;
}

解决方案是将 $places 更改为 {$places}[0]

$places 数组包含关键字,例如餐厅或商店。所以 [0] 指的是 json 中的第一个,这就是需要它的原因。

【问题讨论】:

  • 去掉美元符号?
  • 你试过->{$places}[0]吗?
  • $places 在第一个循环中没有真正引用但在第二个循环中失败时,你为什么要使用foreach ($this->placesCachingTypes as $places) { 循环?
  • 为什么称其为“解析 json”?这就是json_decode() 所做的。所有使用其结果的东西都只是处理数组和对象,它不再是 JSON。
  • 终极答案成功了!

标签: php json string parsing foreach


【解决方案1】:

为什么在第一个循环中有这个:

json[0]->restaurant[0]
json[0]->$restaurant[0]

但是接下来你有:

json[0]->$places[0]
json[0]->$places[0]

也许您对 JSON 的解析不正确,应该是:

foreach ($this->placesCachingTypes as $places) {
  $places_location_lat = $json_decoded->json[0]->places[0]->geometry->location->lat;
  $places_location_lng = $json_decoded->json[0]->places[0]->geometry->location->lng;
}

然后在第一个循环中,您应该进行类似的编辑以摆脱$restaurant[0]

foreach ($this->placesCachingTypes as $places) {
  $places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
  $places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}

然后,当您通过foreach ($this->placesCachingTypes as $places) { 循环时,不清楚$places 的值是多少。使用 $places 的值循环遍历的内容是没有意义的。也许在$json_decoded->json[0]-> 的循环对象中分配$places 是您问题的根源?需要您提供更多信息来确认这一点。

【讨论】:

    猜你喜欢
    • 2010-11-07
    • 2010-11-02
    • 2014-01-01
    • 2016-07-30
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多