Reputation: 73
I have a search that I am developing for a local consignment shop using their POS's API. My code pulls data using this code:
$search = $_GET['search'];
$data = array('key' => $API_KEY,
/*'consignorId' => '1',*/
'query' => $search,
'includeItemsWithQuantityZero' => 'false');
$data_string = json_encode($data);
$context = stream_context_create(array(
'http' => array(
'method' => "POST",
'header' => "Accept: application/json\r\n".
"Content-Type: application/json\r\n",
'content' => $data_string
)
));
$result = file_get_contents('https://user.traxia.com/app/api/inventory', false, $context);
Which returns a json output:
{"results":[{"name":"BKE ","category":"Jeans","sku":"64SA6Z","description":"","color":"blue","size":"4","consignorId":"20579","expireDate":"08/10/2014","startDate":"05/12/2014","status":"ACTIVE","quantity":1,"cost":0,"retail":2500,"discount":0,"buyersFee":200,"images":[],"consignmentItem":true,"doNotDiscount":false,"currentPrice":2700},{"name":"BKE","category":"Shorts","sku":"EUTU4Z","description":"","color":"blue","size":"10","consignorId":"687517","expireDate":"08/07/2014","startDate":"05/09/2014","status":"ACTIVE","quantity":1,"cost":0,"retail":1000,"discount":0,"buyersFee":90,"images":[],"consignmentItem":true,"doNotDiscount":false,"currentPrice":1090},
Which I decode with this code:
$jsonData = $result;
$phpArray = json_decode($jsonData, true);
$phpArray = $phpArray['results'];
foreach ($phpArray as $key => $value) {
print_r("<h2>$key</h2>");
foreach ($value as $k => $v) {
print_r("$k | $v <br />");
}
}
Which returns a page that looks like (with this for all results):
Which I would like to have arrange into a table. Is there a simple way to do this/is it even possible? Thanks!
Upvotes: 0
Views: 213
Reputation: 8872
you want to write something like this
<table border="1" cellpadding="8" cellspacing="0" style="border-collapse: collapse">
<!-- border, cellspacing, and cellpadding attributes are not recommended; only included for example's conciseness -->
<thead>
<tr>
<?php
foreach(array_keys($phpArray[0]) as $k) {
echo "<th>$k</th>";
}
?>
</tr>
</thead>
<tbody>
<?php
foreach($phpArray as $key => $values) {
echo '<tr>';
foreach($values as $v) {
echo "<td>" . implode('<br /> ', (array)$v) . "</td>";
}
echo '</tr>';
}
?>
</tbody>
</table>
Upvotes: 0
Reputation: 2314
It's fairly simple to add a table structure into your loop -
foreach ($phpArray as $key => $value) {
print_r("<h2>$key</h2>");
echo "<table>";
foreach ($value as $k => $v) {
print_r("<tr><td>$k</td><td>$v </td></tr>");
}
echo "</table>";
}
Or, if you want all that info in the same row (assuming there are multiple items being displayed) :
echo "<table>";
foreach ($phpArray as $key => $value) {
print_r("<tr><td>$key</td>");
foreach ($value as $k => $v) {
print_r("<td>$k</td><td>$v</td>");
}
echo "</tr>";
}
echo "</table>";
Upvotes: 1