【问题标题】:How to access sub array in JSON - PHP如何访问 JSON 中的子数组 - PHP
【发布时间】:2014-02-06 16:37:15
【问题描述】:

我已经发布了部分内容.. 但这是一个不同的问题

我有以下

foreach ($results['comments'] as $item) {

  echo 'Date: '. $item['created_at'] .'<br/>';
  echo 'Description : '. $item['html_body'] .'<br/>';
  echo 'Attachments : '. $item['attacments->url'] .'<br/>';
  echo 'Filename : '. $item['file_name'] .'<br/>';
  echo "<br>";
}

所以基本上,我的日期和描述有效,但附件不起作用,b/c 我认为这不是获取数组数组中的对象的正确方法吗?希望我解释正确。

cmets 数组将所有日期作为单个对象,描述也是如此,然后它有这个尾随。

[public] => 1 [trusted] => 1 [attachments] => Array ( [0] => Array ( [url] => https://url/api/v2/attachments/IDHERE.json [id] => ID#[file_name] => name of file here

【问题讨论】:

  • 试试$item['attachments'][0]['url']
  • file_name 怎么样?会是 $item['attachments'][0]['url'][0]['id'][0]['file_name'] @Nouphal.M

标签: php arrays json


【解决方案1】:

看看你的数组转储

[public] => 1
[trusted] => 1
[attachments] => Array (
    [0] => Array (
        [url] => https://url/api/v2/attachments/IDHERE.json
        [id] => ID#
        [file_name] => name of file here

获取如下值:

$Attachments = $item['attachments'];
$AttachmentsUrl = $Attachments[0]['url'];
$Attachmentsid = $Attachments[0]['id'];
$AttachmentsFileName = $Attachments[0]['file_name'];

【讨论】:

  • 我能问一下吗,因为代码给了我一个 PHP Notice: Undefined offset: 0 的错误,我不能用数组的名称代替吗? @meda 看起来怎么样
  • @user3100345 如果抛出错误,则表示$Attachments[0] 在该索引处没有任何元素
  • 我应该放一个if语句吗?
  • @user3100345 是的,检查是否设置了附件数组,也许不是所有的 cmets 都有附件,看到这个 answer 巧合的是它类似于你的情况
猜你喜欢
  • 1970-01-01
  • 2016-12-31
  • 2023-02-04
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-28
相关资源
最近更新 更多