Skip to content

Instantly share code, notes, and snippets.

@trafficinc
Created July 20, 2022 14:40
Show Gist options
  • Save trafficinc/2037c9d8a3785979bbe43bf15ebdbd3b to your computer and use it in GitHub Desktop.
Save trafficinc/2037c9d8a3785979bbe43bf15ebdbd3b to your computer and use it in GitHub Desktop.
Get API data to display in a HTML table
<?php
/*
* APIData::get(string $name) : array
*
* v1/people - array(array(name, phoneNumber, address, occupation), ...)
* v1/jobs - array(array(occupation, salary, numberOfPeople), ...)
* v1/employers - array(array(businessName, address, goodOrService), ...)
*
* Given a $name, return an HTML table displaying the data the API call returns
*
*/
class APICall {
private $name = '';
private $fields = array();
public function APICall(string $name, array $fields){
$this->name = $name;
$this->fields = $fields;
}
private static function getRow(array $data, bool $isHeader = false) : string {
$ret = '<tr>';
foreach($data as $oneData){
$ret .= ($isHeader?'<th>':'<td>').$oneData.($isHeader?'</th>':'</td>');
}
$ret .= '</tr>';
return $ret;
}
private function getTableHeader() : string {
return '<thead>'.ApiCall::getRow($this->fields, '<th>', '</th>') . '</thead>';
}
public function getHTMLTable() : string {
$data = $this->get();
$rows = array($this->getTableHeader());
foreach($data as $oneRowData){
$rows[] = ApiCall::getRow($oneRowData);
}
$tableRows = implode('', $rows);
return '<table>'.$tableRows.'</table>';
}
private function get() : array {
return APIData::get($this->name);
}
}
$apiCall = new ApiCall('v1/people', array('name', 'phoneNumber', 'address', 'occupation'));
print($apiCall->getHTMLTable());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment