So i have 0 experience with array's and putting them into a table. I tried google but there are no good results
Currently my script is this
<?php
$cats = explode("|", $_POST['cat_name']);
echo $cats[0]; // cat_id
?>
<?php
$url = 'http://services.runescape.com/m=itemdb_rs/api/catalogue/items.json?category='.$cats[0].'&alpha=a&page=1';
$result = file_get_contents($url);
$jsonArray = json_decode($result);
print_r($jsonArray);
?>
with this as a result:
1{"total":5,"items":[{"icon":"http://services.runescape.com/m=itemdb_rs/4173_obj_sprite.gif?id=4798","icon_large":"http://services.runescape.com/m=itemdb_rs/4173_obj_big.gif?id=4798","id":4798,"type":"Ammo","typeIcon":"http://www.runescape.com/img/categories/Ammo","name":"Adamant
brutal","description":"Blunt adamantite
arrow...ouch","current":{"trend":"neutral","price":222},"today":{"trend":"neutral","price":0}},{"icon":"http://services.runescape.com/m=itemdb_rs/4173_obj_sprite.gif?id=810","icon_large":"http://services.runescape.com/m=itemdb_rs/4173_obj_big.gif?id=810","id":810,"type":"Ammo","typeIcon":"http://www.runescape.com/img/categories/Ammo","name":"Adamant
dart","description":"A deadly throwing dart with an adamant
tip.","current":{"trend":"neutral","price":11},"today":{"trend":"neutral","price":0}},{"icon":"http://services.runescape.com/m=itemdb_rs/4173_obj_sprite.gif?id=829","icon_large":"http://services.runescape.com/m=itemdb_rs/4173_obj_big.gif?id=829","id":829,"type":"Ammo","typeIcon":"http://www.runescape.com/img/categories/Ammo","name":"Adamant
javelin","description":"An adamant tipped
javelin.","current":{"trend":"neutral","price":64},"today":{"trend":"positive","price":"+1"}},{"icon":"http://services.runescape.com/m=itemdb_rs/4173_obj_sprite.gif?id=867","icon_large":"http://services.runescape.com/m=itemdb_rs/4173_obj_big.gif?id=867","id":867,"type":"Ammo","typeIcon":"http://www.runescape.com/img/categories/Ammo","name":"Adamant
knife","description":"A finely balanced throwing
knife.","current":{"trend":"neutral","price":23},"today":{"trend":"neutral","price":0}},{"icon":"http://services.runescape.com/m=itemdb_rs/4173_obj_sprite.gif?id=804","icon_large":"http://services.runescape.com/m=itemdb_rs/4173_obj_big.gif?id=804","id":804,"type":"Ammo","typeIcon":"http://www.runescape.com/img/categories/Ammo","name":"Adamant
throwing axe","description":"A finely balanced throwing
axe.","current":{"trend":"neutral","price":180},"today":{"trend":"neutral","price":0}}]}
So my question is : How do i put this into a table?
Something like this should do it:
<?php
echo "<table>";
foreach($jsonArray["items"] as $item) {
echo "<tr>
<td>" . $item["id"] . "</td><td>
<td>" . htmlspecialchars($item["type"]) . "</td><td>
<td>" . htmlspecialchars($item["name"]) . "</td><td>
<td><img src='" . $item["icon"] . "'></td></tr>";
}
echo "</table>";
?>
Related
I'm working on a script that will retrieve API information of the 'near earth objects' from NASA's website. User selects date, api grabs the information and displays it. How do I fix the foreach in this script? would appreciate some help with this.
$jsonAsteroids = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($jsonAsteroids, true);
echo "<h4>Retrieving the first element (i.e. \"links\") of the JSON structure</h4>";
var_dump( $data["links"]);
echo "<h4>Retrieving the first element (i.e. \"next\") inside the \"links\" element</h4>";
echo( $data["links"]["next"]);
You were very close. Your main issue was that you used json_decode(..., true); which gives you an array, but then used the object->property syntax instead of object['property']. My suggestion is to use json_decode without the 2nd argument in this case.
Finally, your 2nd foreach was malformed.
<?php
$result = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($result);
foreach ($data->near_earth_objects as $date => $objects) {
echo "<p>" . count($objects) . " objects detected on $date</p>";
echo "<ol>";
foreach ($objects as $object) {
echo "<li>" . $object->name . " <a href='" . $object->nasa_jpl_url . "'>" . $object->nasa_jpl_url . "</a><br>";
echo "Diameter of the object: " . $object->estimated_diameter->meters->estimated_diameter_min . "-" . $object->estimated_diameter->meters->estimated_diameter_max . " metres<br>";
echo "<ul>";
foreach ($object->close_approach_data as $close_approach) {
echo "<li>Close approach: " . $close_approach->close_approach_date . " traveling at a velocity of " . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "missing " . $close_approach->orbiting_body . " by " . $close_approach->miss_distance->kilometers . " km</li> ";
}
echo "</ul>";
}
echo "</ol>";
}
I'm just getting into php, html etc and am trying to resolve an issue at work. Please be patient with my lack of experience.
I have a csv file, TEST2.csv. it is as follows advisor,guest,stockNumber,part,qty,partnote1,partnote2,status that I am putting on a webpage so that our staff can select their advisor number and see the status of their parts. The report we export from our system is in csv and has columns that I do not want to show on this report.
(before I hear I should learn another format to display this, I know, Im under a time constraint and need something quick and rudimentary for now)
Everything works well but it does not show column 7, only up to 4. I want it to skip 5,6 Here's the monster i've created:
<table id="demo">
<tbody>
<?php
$fp = fopen ( "TEST2.csv" , "r" );
$wantedColumns = array(0,1,2,3,4,7);
while (( $data = fgetcsv ( $fp , 1000 , "," )) !== FALSE ) {
$i = 0;
echo "<tr>";
foreach($data as $row) {
if (!in_array($i,$wantedColumns)) continue;
echo "<td>" . $row . "</td>";
$i++ ;
}
echo "/<tr>";
}
fclose ( $fp );
?>
`
Any help would be greatly appreciated!
Using simple array syntax with [index] your code will be:
$fp = fopen ( "TEST2.csv" , "r" );
while (( $data = fgetcsv ( $fp , 1000 , "," )) !== FALSE ) {
echo "<tr>";
echo "<td>" . $data[0] . "</td>";
echo "<td>" . $data[1] . "</td>";
echo "<td>" . $data[2] . "</td>";
echo "<td>" . $data[3] . "</td>";
echo "<td>" . $data[4] . "</td>";
echo "<td>" . $data[7] . "</td>";
echo "</tr>";
}
fclose ( $fp );
I have been working on this for awhile and I am maybe making this more difficult than it is. Any shared knowledge would be very much appreciated.
My code calls data using an API, I was able to display it as a ordered list but I wanted to make it more presentable using a table format.
Ideally I the results to be displayed grouped by day.
Below is what I have created so far, but it is not outputting anything currently:
echo "<table>";
echo "<tr>";
echo "<th>Date</th>";
echo "<th>Number of Asteroids</th>";
echo "</tr>";
echo "<tr>";
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<td>" . $close_approach->close_approach_date . "</td>";
foreach ($data->near_earth_objects as $date => $count) {
echo"<td>" . sizeof($count) . "</td></tr>";
}
}
echo "<tr>";
echo "<th>Asteroid Name</th>";
echo "<th>Asteroid Size</th>";
echo "<th>Velocity</th>";
echo "<th>Passing Earth By</th>";
echo "</tr>";
echo "<tr>";
foreach ($data->near_earth_objects->$date as $near_earth_object) {
echo "<td>" . $near_earth_object->name . " <a href='" . $near_earth_object->nasa_jpl_url . "'>" . $near_earth_object->nasa_jpl_url . "</td>";
echo "<td>" . $near_earth_object->estimated_diameter->meters->estimated_diameter_min . " metres</td>";
}
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<td>" . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "</td><td>". $close_approach->miss_distance->kilometers . " km</td></tr> ";
}
echo"</table>";
You should avoid echoing HTML code whenever possible. You can use PHP Short tags <?= and ?> to inject PHP into your HTML code. This line
echo "<td>" . $close_approach->close_approach_date . "</td>";
can then be changed to
<td><?=$close_approach->close_approach_date?></td>
Furthermore I don't see any PHP opening and closing tags (<?php and ?>) to start and end your PHP code (although this may just be lacking in your example)
You're only looping through your table data <td> tags not your table row <tr> tags. You have to include these in your loop to keep creating a new table rows for every item in your loop:
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<tr>";
Finally, PHP offers an alternative syntax for control structures. Check out the PHP documentation
PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
You can use this to improve your existing code:
foreach ($data->near_earth_objects->$date as $near_earth_object) {
echo "<td>" . $near_earth_object->name . " <a href='" . $near_earth_object->nasa_jpl_url . "'>" . $near_earth_object->nasa_jpl_url . "</td>";
echo "<td>" . $near_earth_object->estimated_diameter->meters->estimated_diameter_min . " metres</td>";
}
And turn it into something like this
foreach ($data->near_earth_objects->$date as $near_earth_object): ?>
<td><?=$near_earth_object->name?> <a href='<?=$near_earth_object->nasa_jpl_url?>'><?=$near_earth_object->nasa_jpl_url?></td>
<td><?=$near_earth_object->estimated_diameter->meters->estimated_diameter_min?> metres</td>
<? endforeach; ?>
I recommend creating the table as you'd like to see it just with HTML and then using PHP to dynamically populate it. What may help is, rather than having PHP echo all of the HTML, just use PHP to populate the data (i.e., separate data from display). Just as an example taken from here:
<?php foreach ($things as $thing): ?>
<li><?php echo $thing; ?></li>
<?php endforeach; ?>
I have an array being collect via a form like below:
<select multiple="multiple" name="contractors[]" >
Input code to save the array in the DB.
$options = $_POST['contractors'];
$serializedoptions = serialize($options);
It saves the array in the DB in the format below, but I cannot display it properly. When I pull the entire It shows:
a:4:{i:0;s:28:Contractor1";i:1;s:15:"Contractor2";i:2;s:10:"Contractor3";}
How can I get it to display in a more readable format?
$result = mysql_query("SELECT * FROM form_2 GROUP BY jobname");
echo "<table border='1'>
<tr>
<th><font size='1'>Job Name</th>
<th><font size='1'>Contractors</th>
<th><font size='1'>Notes</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><font size='1'>" . $row['jobname'] . "</font></td>";
echo "<td><font size='1'>" . $row['contractors'] . "</font></td>";
echo "<td><font size='1'>" . $row['notes'] . "</font></td>";
echo "</tr>";
}
echo "</table>";
That which is serialized must be unserialized. Just use the unserialize function on the data before working with it. In your case, an array will be returned.
http://php.net/manual/en/function.unserialize.php
$options = unserialize($serializedoptions);
Other languages can unserialize PHP serialize() as well if you find supporting code for it. For example, here is one for JavaScript: http://phpjs.org/functions/unserialize/
EDIT:
Updating the code you added, you can display it like any other PHP variable once you unserialize the value.
<?php
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><font size='1'>" . $row['jobname'] . "</font></td>";
echo "<td><font size='1'>";
$contractors = unserialize($row['contractors']);
foreach ($contractors as $contractor)
echo htmlspecialchars($contractor).'<br/>';
echo "</font></td>";
echo "<td><font size='1'>" . $row['notes'] . "</font></td>";
echo "</tr>";
}
?>
Use print_r on the unserialized array:
print_r(unserialize($serializedArray));
You can use the unserialize command. You can then echo it using var_dump() or print_r().
In the HTML Table above, you would have to further break down the result for $row['contractors'].
So first, you would unserialize that value, so lets say
$contractors = unserialize($row['contractors']);
Then you can iterate through the new array of $contractors, and echoing a after each one, all inside the same TD.
I can't actually unserialize the above serialized data, so I can't write the loop for you.
Use unserialize($serializedoptions) to convert it back into an array. If you want to view it, use var_dump($unserialized)
I know there are lots of plugins there to display a table with static headers. My issue is that i have a for loop which returns the values under this table:
foreach($ftsProducts as $x) {
$content .= "<tr class='highlight'>
<td class='reportCell' title='" . $x['BaseCode'] . "'>" . $x['Description'] . "</td>
<td class='reportCell'>" . $x['Fit'] . "</td>";
foreach($sizes as $y) {
$content .= "<td class='reportCell'>" . $x[$y] . "</td>";
}
$content .= "<td style='font-weight: bold; text-align: center;'>" . $x['Total'] . "</td>
</tr>";
}
$content .= "</table>";
Anyone got any suggestions or advice.
Many thanks
As far as i understand, your problem is not related to PHP, but to HTML and CSS. Static headers are tricky to achieve and there are probably browsers, which won't let you do them. Have a look at this solution, for example:
http://www.imaputz.com/cssStuff/bigFourVersion.html
By viewing the source of the page, it should -- imo -- be obvious how you have to build your table with PHP.
HTH