【问题标题】:PHP loop to retrieve each instance of a specific piece of data from within decoded JSONPHP循环从解码的JSON中检索特定数据的每个实例
【发布时间】:2019-07-28 10:44:46
【问题描述】:

我正在尝试编写一个循环来列出 JSON 数据中的所有 uiduid 跨越两个类别(衬衫和裤子)。以下是我到目前为止所拥有的。任何帮助是极大的赞赏。

当前代码和 JSON

$url = 'http://foothillertech.com/student/webdesign/2018/2018benrud2/projects/retail/data2.json';
$jsonData = file_get_contents($url);
$data = json_decode($jsonData, true);

我可以手动获取每个uid - $data['shirts'][0]['uid'],但我正在寻找一种方法来循环遍历数据以返回衬衫和裤子类别中的所有 uid。

谢谢!

这是解决我问题的代码。

感谢@Don't Panic 的帮助!

foreach ($data as $item_type => $items) {
    foreach ($items as $item) {
        $uids[] = $item['uid'];
        echo $uids[$i]."<br>";
        $i++;
    }
}

【问题讨论】:

  • foreach 带有嵌套的foreach?还是foreacharray_column?其他可用选项。
  • 可能是array_map_assocarray_walk

标签: php json loops foreach


【解决方案1】:

您可以合并第二级数组(衬衫和裤子键)并从结果中获取 uid 列。

$uids = array_column(array_merge(...array_values($data)), 'uid');

这个表达式的细节从内到外(PREVIOUS表示上一步的结果):

  • array_values($data) 将外部数组('shirts','pants')的字符串键转换为数字
  • array_merge(... PREVIOUS ) 合并两个内部数组,使用argument unpacking 将它们传递给array_merge。 (需要前面的array_values 步骤,因为参数解包不适用于带有字符串键的数组。)
  • array_column( PREVIOUS , 'uid') 从前面步骤生成的合并数组中获取所有 'uid' 值

不过,这是一种相当简单的花哨方式。如果只使用嵌套循环,代码会更清晰。

foreach ($data as $item_type => $items) {
    foreach ($items as $item) {
        $uids[] = $item['uid'];
    }
}

【讨论】:

  • 这是错误的。它甚至没有考虑主 $data array 中的“衬衫”键。此解决方案在具有 uid 的二级数组中获取任何内容。因此,如果有一些名为“pants”或“hats”的键,那么它将通过所有这些键。
  • 是的,我相信这就是目标。 OP 声明:“我正在寻找一种方法来循环遍历数据以返回衬衫和裤子类别中的所有 uid。”
  • 好的。我收回我的评论。
  • @Don'tPanic 感谢您的帮助!我正在努力更好地理解您的第一个解决方案,因为我相信它是一个“更高级别”的解决方案,我相信我将来需要使用它。如果可能,您能否在该解释中添加更多细节?再次感谢!
【解决方案2】:

正如@jon-stirling 提到的,您可以使用array_column() 从数组的符号列中提取值。它还做了许多超出您问题范围的其他事情。查看http://php.net/manual/en/function.array-column.php

对于您的示例,以下代码应该为您提供从$data['shirts'] 中提取的所有uid

$url = 'http://foothillertech.com/student/webdesign/2018/2018benrud2/projects/retail/data2.json';
$jsonData = file_get_contents($url);
$data = json_decode($jsonData, true);
$shirtsUids = array_column($data['shirts'], 'uid');
$pantsUids = array_column($data['pants'], 'uid');

// Then you can use $shirtsUids and $pantsUids as you see fit.

确保 $data 数组有一个名为 shirt 的键,否则会抛出错误或警告。

为避免导致错误,我使用 Null 合并运算符 (??) 将不确定值默认为可接受的值。所以我将使用$data['shirts'] ?? []。但同样,请确保 $data['shirts'] 是一个数组。

$url = 'http://foothillertech.com/student/webdesign/2018/2018benrud2/projects/retail/data2.json';
$jsonData = file_get_contents($url);
$data = json_decode($jsonData, true);
$shirtsUids = array_column($data['shirts'] ?? [], 'uid');
$pantsUids = array_column($data['pants'] ?? [], 'uid');

// Then you can use $shirtsUids and $pantsUids as you see fit.

【讨论】:

    猜你喜欢
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 2017-05-03
    相关资源
    最近更新 更多