1

This is my first time coding in PHP. I have this json file (screenshot). json file

It contains a name and sources array. I need to break up this "sources" array by the fields that are in the array (name, url, description, groupfields, and searchfields). I have used the json_decode function but I am stuck on how to break up things in this file. Here is my code so far. Any help/hints/tips would be appreciated. Mainly, I am confused about accessing the various elements and subelements in the sources array from the file. More background info: There is an html form and I am trying to add all the name elements from the sources array as options in the select element of the form.

$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
?>
Kevin
  • 13
  • 2
  • Welcome to Stack Overflow! Please [edit your question](https://stackoverflow.com/posts/59201418/edit) to include your JSON file *directly in the question*, **not** as an attached image. This will make it easier for us to analyze your code and help you find a solution. – Das_Geek Dec 05 '19 at 18:55

2 Answers2

0

If I am getting it correctly, you can use foreach and nested foreach to get the values within each array.

$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>';

For more information on foreach statement in php, check this SO question. How does PHP 'foreach' actually work?

Ajay Singh
  • 692
  • 8
  • 19
0

You could also use array_column to pick out just the names, then implode it into a string.

echo '
<select name="sourcedata">
  <option>'.implode('</option><option>', array_column($result['sources'], 'name')).'</option>
</select>';
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106