So I have a JSON output here https://squad-servers.com/api/?object=servers&element=detail&key=fupxq9hl1vkxb4yxhkggada7e0jz8p6w1
What I'd like to do is get this into a HTML Table to create my own status page as such, this is where I got with it.
<?php
$json=file_get_contents("https://squad-servers.com/api/?object=servers&element=detail&key=fupxq9hl1vkxb4yxhkggada7e0jz8p6w1");
$data = json_decode($json);
print_r($data);
?>
stdClass Object
(
[id] => 2272
[name] => [ZXD] Zulu X-Ray Delta EU/UK #2
[address] => 164.132.202.16
[port] => 7797
[private] => 0
[password] => 0
[query_port] => 27175
[location] => United Kingdom
[hostname] => Zulu X-Ray Delta EU/UK #2
[map] => Kokan AAS v1
[is_online] => 0
[players] => 0
[maxplayers] => 72
[version] => a-8.8.116.11628
[platform] => windows
[uptime] => 97
[score] => 4
[rank] => 81
[votes] => 0
[favorited] => 0
[comments] => 0
[url] => https://squad-servers.com/server/2272/
[last_check] => December 7th, 2016 08:50 AM EST
[last_online] => December 7th, 2016 07:25 AM EST
)
But how can I get this into a table, so I can echo / print out each part of the array?
Many thanks,
$tbl = "<table><tr><th>".implode('</th><th>',array_keys((array)$data))."</th></tr>";
$tbl .= "<tr><td>".implode('</td><td>',(array)$data)."</td></tr></table>";
print $tbl;
...on way to rome.
$head=array();
$body=array();
foreach($data as $k=>$v){
$head[]="<th>$k</th>";
$body[]="<td>$v</td>";
}
print "<table><tr>".implode('',$head)."</tr><tr>".implode('',$body)."</tr></table>";
...another way.
(every used function can be found at php.net)
This will only work on your example. Not every json output can be easy printed into an html-table.
You can print each value using foreach:
foreach ($data as $key => $value) {
echo $value;
}
http://php.net/manual/en/control-structures.foreach.php
All you need is to call print_r($data->name); so echo $data->name with current api call.
if you have more than one result:
<table>
<?php foreach ($object as $value) {
echo '<tr>';
echo '<td>'.$value->name.'</td>';
echo '<td>'.$value->address.'</td>';
echo '<td>'.$value->hostname.'</td>';
echo '<td>'.$value->uptime.'</td>';
echo '</tr>';
}
}
?>
</table>
json_decode has an optional second parameter determining whether you want to have an associated array. This parameter is false by default and therefore you get a standard object, which is much more difficult to handle. Instead, make sure that you have an associated array:
$data = json_decode($json, true);
foreach ($data as $key => $value) {
//Do something with $key and $value
}
Related
i'm parsing a json file (api rest) but i can't solve a problem. This is the json file.
Array
(
[110197275197292] => Array
(
[mid] => 110197275197292
[home] => FC Den Bosch
[away] => SC Telstar
[country_leagues] => Netherlands - Eerste Divisie
[leagues] => Eerste Divisie
[country] => Netherlands
[score] =>
[home_score] => 0
[away_score] => 0
[periodID] =>
[periodTXT] =>
[periodTime] => 1632923759
[startTime] => 1633111200
[lastUpdateTime] => 1632923357
[minutes] => 0
[status] => 1
[importancy] => 281
[odds] => Array
(
[home] => 2.45
[draw] => 3.70
[away] => 2.40
[1st-1] => 2.90
[1st-0] => 2.35
[1st-2] => 2.87
[2nd-1] => 2.70
[2nd-0] => 2.70
[2nd-2] => 2.65
with this code below i print the value of the array, and work.
foreach ($response as $key1 => $value1){
echo $response[$key1]['home'] .'<br>';
}
Now i would insert the value of the array in a variable, something like that
foreach ($response as $key1 => $value1){
$prova = $response[$key1]['home'];
}
<?php echo $prova; ?>
This way I could recall it in an html table. This code print me only one value of the array and does not loop (foreach). The value that prints in this case is Nashville SC which is a value found in the json file. Where is my mistake? there is a way to encapsulate array values in a variable and then recall it later in the html code?
You are always overwriting the $prova variable with the home team. You should either convert $prova to an array and work with it or move the echo inside your loop to print everything.
Moreover you should use more distinct names to your variables so both we and you understand your code.
//1. echo way
foreach ($response as $matchDate => $matchData){
$prova = $matchData['home'];
echo $prova;
}
//2. array way
$prova = [];
foreach ($response as $matchDate => $matchData){
$prova[$matchDate] = $matchData['home'];
}
var_dump($prova); //This will print the whole array of home teams.
I have an array like this:
Array (
[0] => Array (
[0] => 510
[1] => 984
[2] => 1045
[3] => 2068
[4] => 1054
[5] => 673
)
[1] => Array (
[0] => 1163
[1] => 1982
[2] => 2067
[3] => 3989
[4] => 1940
[5] => 1242
)
[2] => Array (
[0] => june
[1] => july
[2] => august
[3] => september
[4] => october
[5] => november
)
)
I want to access only one of the arrays within the array at a time and echo them out.
For example, I would get: 510, 984, 1045, 2068, 1054, and 673 as one result.
I've looked at multiple threads and answers but nothing that quite solves my issue, I've been able to print out all the values but I just want some specifically.
I'd store it in the variable: $array_item
My most recent attempt was:
foreach ($array_item as $inner) {
if (is_array($inner)) {
foreach ($inner[0] as $value) {
echo "$value \n";
}
}
}
Which gives me: Warning: Invalid argument supplied for foreach().
I thought for sure that would work, what am I doing wrong?
In your code $inner[0] is one of the inner array elements, like 510. You can't loop over that.
If you just want to loop over $array_item[0], don't loop over the whole array.
if (is_array($array_item[0])) {
foreach ($array_item[0] as $value) {
echo "$value\n";
}
}
Does is_array($array_item) return true?
if (is_array($array_item)) {
foreach ($array_item) {
if (is_array($inner)) {
foreach ($inner as $value) {
echo "$value \n";
}
}
}
}
Edit: Also, $inner[0] is not an array. $inner is the array.
I would use implode, http://php.net/manual/en/function.implode.php
foreach($array_items as $items) {
echo implode(', ', $items);
}
I see that a comment was made that he wants only the first array to be outputted and not all of them.
if (is_array($array_item[0])) {
echo implode(PHP_EOL, $array_item[0]);
}
You never can tell what could solve a problem
$array_group = array();
if (isset($array_item[0]) and is_array($array_item[0])) {
foreach ($array_item[0] as $value) {
$array_group[] = $value;
}
$array_group should output
Array
(
[0] => 510
[1] => 984
[2] => 1045
[3] => 2068
[4] => 1054
[5] => 673
)
Need some help figuring this out. I have a JSON array going to a php file after the submit is clicked via ajax. Once decoded on the php side, it looks like this:
Array
[0] => Array
(
[ID] => 409
[ChangeType] => CHANGE_SEAT_TO
[Name] => John Doe
[Seat] =>
[setTo] => 4-2
[PreviousSeatValue] =>
[PreviousSeatNewValue] => Y
)
[1] => Array
(
[ID] => 278
[ChangeType] => CHANGE_SEAT_TO
[Name] => John Test
[Seat] => 4-1
[setTo] => 4-3
[PreviousSeatValue] => Y
[PreviousSeatNewValue] => Y
)
[2] => Array
(
[ID] => 305
[ChangeType] => REMOVESEAT
[Name] => John Blue
[Seat] => 3-6
[setTo] => 0
)
[3] => Array
(
[ID] => 314
[ChangeType] => CHANGE_SEAT_TO
[Name] => John Red
[Seat] => 3-4
[setTo] => 3-6
[PreviousSeatValue] => Y
[PreviousSeatNewValue] => Y
)
Main Goal:
What im trying to do is loop through all the arrays and if changetype matches a string("CHANGE_SEAT_TO" or "REMOVESEAT"), execute a SQL statement. Im having issues assigning variables to the different key values in the matching arrays during a loop. Here is what I have so far:
$obj = json_decode($_POST['myData'], TRUE);
foreach ($obj as $innerArray){
foreach($innerArray as $key => $value){
$$key = $value;
if($value === "CHANGE_SEAT_TO"){
echo $ID;
echo $setTo;
}
if($value === "REMOVESEAT"){
echo $ID;
echo $setTo;
}
}
}
Now obviously this is set up for just testing purposes(i have the echo's displaying in the console log after successful ajax). With this setup, I am able to successfully echo out the ID of the matching elements but if I try any other one, the variable is undefined. Can anyone explain why this is happening and offer up a suggestion to the main goal? Thanks in advance.
You need only one foreach(), check the modified code
<?php
$obj = json_decode($_POST['myData'], TRUE);
foreach ($obj as $innerArray){
if($innerArray['ChangeType'] == 'CHANGE_SEAT_TO') {
// do stuff
$id = $innerArray['ID'];
// get rest of values in same way
} else if($innerArray['ChangeType'] == 'REMOVESEAT') {
// do stuff
$id = $innerArray['ID'];
// get rest of values in same way
}
}
Try something like this:
foreach ($obj as $value) {
if ($value['ChangeType'] == 'CHANGE_SEAT_TO') {
echo $value['ID'];
echo $value['setTo'];
} elseif ($value['ChangeType'] == 'REMOVESEAT') {
echo $value['ID'];
echo $value['setTo'];
}
}
I am trying to read out this nested array with a foreach loop but get an error "invalid argument supplied in foreach"
Array (
[regenerated] => 1302668837
[id] => 2
[qty] => 1
[price] => 1200
[name] => support
[optione] =>
[cart_contents] => Array (
[c4ca4238a0b923820dcc509a6f75849b] => Array (
[rowid] => c4ca4238a0b923820dcc509a6f75849b
[id] => 1
[qty] => 1
[price] => 29.95
[name] => Training DVD
[optione] =>
[subtotal] => 29.95
)
[c81e728d9d4c2f636f067f89cc14862c] => Array (
[rowid] => c81e728d9d4c2f636f067f89cc14862c
[id] => 2
[qty] => 1
[price] => 1200
[name] => support
[optione] =>
[subtotal] => 1200
)
[total_items] => 2
[cart_total] => 1229.95
)
[johndoe] => audio
[totalItems] => 2
)
$cart_contentz = $_SESSION['cart_contents'];
foreach($cart_contentz as $itemz => $valuez) {
foreach($valuez as $key1 => $value1) {
echo "$key1: $value1<br>";
}
the first level of your main array has items that are sub-arrays and some that are not. Your second loop doesn't work on non-array items.
Thus, your code should be:
foreach($cart_contentz as $itemz => $valuez) {
if (is_array($valuez)) {
foreach($valuez as $key1 => $value1) {
echo "$key1: $value1<br>";
}
} else {
echo "$itemz: $valuez<br>";
}
}
you'll need to load that array into your $_SESSOIN['cart_contents'] which may have been done. secondly, your inner foreach is acting on the values of that array which are not arrays. I'm fairly certain that the inner foreach is causing your woes. Also, your Array may just be for illustrating what's in $_SESSION['cart_contents'], but adding quotation marks instead of square brackets around the keys will make it more uniform and easier to read.
Update:
after seeing the reformatted code, thanks #AgentConundrum, now I can more clearly see the issue. Try adding an if(is_array($valuez)) around your inner foreach.
Maybe to use recursion:
function printArray($array, $parent=false, $level=0) {
if (!($parent === false)) echo "<b>".str_pad('',($level-1)*4,"-")."[$parent] =></b><br />\n";
foreach ($array as $key=>$value) {
if (!is_array($value)) echo str_pad('',$level*4,"-")."[$key] => $value<br />\n";
else printArray($value, $key, $level+1);
}
}
print_array($your_array);
I need help sorting [Time] data from in this array in php. For a given day, the time is NOT in order.
Is there a way to sort this? Thanks.
Array ( [0] => Array ( )
[1] => Array (
[Server] => server1.name
[Date] => Sun Aug 22 2010
[Set] => db2.bak_lvm
[Time] => 06:00:02
[Duration] => 01:28:12
[Size] => 72.05 GB
[Status] => Succeeded )
[2] => Array ( [Server] => server1.name
[Date] => Sun Aug 22 2010
[Set] => db2.bak_lvm
[Time] => 00:00:03
[Duration] => 01:49:37
[Size] => 187.24 GB
[Status] => Succeeded )
[3] => Array ( [Server] => server1.name
[Date] => Sun Aug 22 2010
[Set] => db3.bak_lvm
[Time] => 23:00:03
[Status] => Unsuccessful )
[4] => Array ( [Server] => server1.name
[Date] => Sun Aug 22 2010
[Set] => db4.bak_lvm
[Time] => 04:00:03
[Duration] => 00:42:36
[Size] => 46.46 GB
[Status] => Succeeded )
Here's my php code, thus far:
<?php
$data = array();
$InputFile = file("test.txt");
foreach ($InputFile as $line){
preg_match_all("/([0-9])-([^=]+)=([^;]+);/", $line, $matches, PREG_SET_ORDER);
$LineData = array();
foreach ($matches as $information)
$LineData[$information[2]] = $information[3];
$data[] = $LineData;
}
$keys = array('Server', 'Date','Set','Time','Duration','Size','Status');
echo '<table id="stats"><tr>';
foreach ($keys as $column)
echo '<th>' . $column . '</th>';
echo '</tr>';
$counter=0;
foreach ($data as $row){
$counter ++;
$class = $counter % 2 === 0 ? 'alt1' : 'alt2';
echo '<tr class="' . $class . '">';
foreach ($keys as $column)
if (isset($row[$column])){
echo '<td>' . $row[$column];
} else {
echo '<td>' . '' . '</td>';
}
}
echo '</table>';
print_r($data);
?>
Updated: Latest sort after using suggested fix by Bill. [Time] is in order, but also need to have it sorted within [Date]
Array ( [0] => Array (
[Server] => server1.name
[Date] => Mon Aug 23 2010
[Set] => db2.bak_lvm
[Time] => 00:00:03
[Duration] => 01:50:24
[Size] => 187.24 GB
[Status] => Succeeded )
[1] => Array ( [Server] => server1.name
[Date] => Mon Aug 23 2010
[Set] => db3.bak_lvm
[Time] => 04:00:02
[Duration] => 00:42:28
[Size] => 46.47 GB
[Status] => Succeeded )
[2] => Array ( [Server] => server1.name
[Date] => Sun Aug 22 2010
[Set] => db3.bak_lvm
[Time] => 04:00:03
[Duration] => 00:42:36
[Size] => 46.46 GB
[Status] => Succeeded )
[3] => Array ( [Server] => server1.name
[Date] => Mon Aug 23 2010
[Set] => db1.bak_lvm
[Time] => 06:00:02
[Duration] => 01:28:24
[Size] => 72.05 GB
[Status] => Succeeded )
[4] => Array ( [Server] => server1.name
[Date] => Sun Aug 22 2010
[Set] => db4.bak_lvm
[Time] => 20:00:03
[Duration] => 04:17:57
[Size] => 426.60 GB
[Status] => Succeeded )
edit: Now that I understand your input data better, I've tested this script.
First I read the data file as you do, but I collect the data field by field directly into a two-dimensional array:
<?php
$data = array();
$InputFile = file("test.txt");
foreach ($InputFile as $line)
{
preg_match_all("/([0-9])-([^=]+)=([^;]+);/", $line, $matches, PREG_SET_ORDER);
foreach ($matches as $information)
{
$id = $information[1];
$field = $information[2];
$value = $information[3];
$data[$id][$field] = $value;
}
}
Next I sort the data array with a user-defined sorting function passed to usort(). Thanks to commenters for suggestions to make this function better.
function comparebydatetime($a, $b) {
$adate = strtotime($a["Date"]." ".$a["Time"]);
$bdate = strtotime($b["Date"]." ".$b["Time"]);
return $adate-$bdate;
}
usort($data, "comparebydatetime");
Now the data is sorted by date and time, so I can simply output it:
$keys = array("Server", "Date","Set","Time","Duration","Size","Status");
echo "<table id='stats'>\n";
echo "<tr>\n";
foreach ($keys as $column)
{
echo "<th>" . htmlspecialchars($column) . "</th>\n";
}
echo "</tr>\n";
$counter=0;
foreach ($data as $row)
{
$counter ++;
$class = $counter % 2 === 0 ? "alt1" : "alt2";
echo "<tr class='" . htmlspecialchars($class) . "'>\n";
foreach ($keys as $column)
{
echo "<td>";
if (isset($row[$column]))
{
echo htmlspecialchars($row[$column]);
}
echo "</td>\n";
}
echo "</tr>\n";
}
echo "</table>";
I've also added some other changes for better PHP style:
Be consistent about indentation.
Use curly-braces even for a block with one statement.
Use htmlspecialchars() for outputting dynamic data (including field names, CSS classes, etc.).
If you are on PHP5.3 already, you could use a Heap (manual|wiki) for this:
class SortByDateTimeDescending extends SplMaxHeap
{
public function compare($a, $b)
{
if(!empty($a['Date']) && !empty($a['Time']) &&
!empty($b['Date']) && !empty($b['Time']))
{
$timestampA = strtotime("{$a['Date']} {$a['Time']}");
$timestampB = strtotime("{$b['Date']} {$b['Time']}");
return $timestampA - $timestampB;
}
return 0;
}
}
$sorter = new SortByDateTimeDescending;
array_map(array($sorter, 'insert'), $data);
You can then foreach over $sorter or, if you want the heap back to an array, use
$sortedData = iterator_to_array($sorter);
If you are not on PHP5.3 yet, you can use the code in the compare function to usort() the data. The order will be reversed though (meaning Ascending). Iterating over the sorted array is easy.
You could also use a SortingIterator to go over the array directly.
Simply put : walk over your array and put each date as the key of each child, then ksort() your resulting array.
Don't forget to, if necessary, translate your date in DateTime before setting it as an array key, so that ksort() can work throught it:
$to_be_sorted = array();
foreach($array as $child) {
$date = new DateTime($child["date"].' '.$child["time"]);
$to_be_sorted[$date] = $child;
}
$sorted = ksort($to_be_sorted);
You'll loose your original keys (0,1,...,4) but I assume that it's not a problem ?