0

I have this code:

$url='MY API';
$json = json_decode( file_get_contents( $url ) );
$res=$json->results;

foreach( $res as $obj ){
    $values=$obj->values;
    
    foreach( $values as $o ){
        echo $o->name . ' ' . $o->value . ' ' . $o->objectTypeId . '<br />';
    }           
}

Getting this output:

country Germany 0-2
title_no_dropdown ADP, ECM Intro 0-1
presented_by PMI Document Solutions, Inc. 0-1
city Munich 0-1
website http://www.pmi-ny.com 0-1
start_date October 24 0-1
time 1200 0-1
type Webinar 0-1
description this is a test 0-2
email bob@hotmail.com 0-1
link Link to partner event 0-1
country United States 0-2
title_no_dropdown ADP, Work Smart from the Start 0-1
state NY 0-1
presented_by PMI Document Solutions, Inc. 0-1
city Corning 0-1
website http://www.pmi-ny.com 0-1
start_date September 24 0-1
time 1000 0-1
type Infoseminar 0-1
description This is a test 0-2
email likwid2@hotmail.com 0-1

How can I get the $o->value as a variable or some way to be able to control the order so I can add them to table cells. Also, how can I create that table with those variable. Thanks.

  • Is $res a 2d Array? Can you add ```console_log( $res );``` to your code and show us the output in your console? If you want to create an array from JSON see the answers in this SO post: https://stackoverflow.com/questions/6739871/how-to-create-an-array-for-json-using-php – EKrol Sep 04 '21 at 21:39
  • I am loop through a nested array with PHP. I need to get control over $o->value so I rearrange the order and add multiple to table cells. – Mark Wroblewski Sep 04 '21 at 21:46
  • If that’s the case you can just use the for loop already in place to create table rows and use the o->value as the content for the rows. There are plenty of resources available to help you already. Hope this helps. https://stackoverflow.com/questions/4746079/how-to-create-a-html-table-from-a-php-array – EKrol Sep 04 '21 at 21:53

1 Answers1

0

Start here: https://www.w3schools.com/html/html_tables.asp - learn how a table is built... and basically add the html before and during the print of your data....

Example: (I did some paraphrasing and removed a loop because I didn't have your values and wanted to illustrate a code that will work with copy/paste :)

 <table>
  <tr>
    <th>Country</th>
    <th>Title</th>
    <th>City</th>
 </tr><?php

//foreach( $res as $obj ){
     $values= ["country1" => "aaa","title1"=>"bbbb","city1" => "tel-aviv"];
     ?><tr><?php
     foreach( $values as $o ){
        echo "<td>" . $o . '</td>';
     }
   ?><tr><?php
// }

?></table>

Even if you bring the other loop back ... remember when a new line begins and when a new <td> begins..

It is important to know where things are positioned since we are looping through values. so the <th>'s will be outside the loops since they come only once... and the <tr>'s <td>'s well that depends on how the data is placed.

Slap some css on this and your good!

Shlomtzion
  • 674
  • 5
  • 12