php - 如何通过键/值在 PHP 中分解这个 json_decoding 文件?
问题描述
这是我第一次用 PHP 编码。我有这个 json 文件(截图)。json文件
它包含一个名称和来源数组。我需要通过数组中的字段(名称、url、描述、组字段和搜索字段)来分解这个“来源”数组。我已经使用了 json_decode 函数,但我被困在如何分解这个文件中的东西。到目前为止,这是我的代码。任何帮助/提示/提示将不胜感激。主要是,我对从文件访问源数组中的各种元素和子元素感到困惑。更多背景信息:有一个 html 表单,我正在尝试将源数组中的所有名称元素作为选项添加到表单的 select 元素中。
$json_data = file_get_contents(SOURCE_URL);
$result = json_decode($json_data, true);
?>
<form action="P4.php" method="get">
Source Data
<select name ="sourcedata"></select> <br> <br>
<?php
$sources = $result['sources'];
#var_dump($sources);
#doing this var_dump successfully dumps the sources array
?>
解决方案
如果我理解正确,您可以使用 foreach 和嵌套的 foreach 来获取每个数组中的值。
$json_data = file_get_contents(SOURCE_URL);
$result = json_decode($json_data, true);
$names = '<select>';
foreach($result['sources'] as $data1) {
// This will add each name inside the array
$names = $names.'<option>'.$data1['name'].'</option>';
// Nest another foreach to go one step further to get values of 'groupfields' array within this name
foreach($data1['groupfields'] as $data2) {
$group_field = $data2;
}
}
$names = $names.'</select>';
有关 php 中 foreach 语句的更多信息,请查看这个 SO question。PHP“foreach”实际上是如何工作的?
推荐阅读
- python - 我如何计算每列和每行的平均值并沿 10*3 数组打印
- laravel - 在 AWS Elastic Beanstalk 上安装 composer 时出错
- c++ - 如何使用模板制作 3D 对象的打印版本?(c++)
- flutter - 在 AlertDialogue 中显示的 RadioListTile 列表中更新选择的问题
- z3 - 如何在 z3py 中连接正则表达式?
- discord - awaitReactions 遇到问题
- python - 使用 Functions Framework for Python 时如何在 Google Cloud Buildpacks 中设置运行时版本?
- algorithm - 二进制搜索以查找布尔数组中的最高真实索引
- prisma - 生成迁移 README 时,Prisma 的名字来自哪里?
- swift - 快速为牛津词典 API 构建数据模型的问题