首页 > 解决方案 > 如何通过键/值在 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
?>

标签: phparraysjson

解决方案


如果我理解正确,您可以使用 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”实际上是如何工作的?


推荐阅读