Send PHP Array data to html table - php

I'm not a PHP pro and would really appreaciate some help with displaying some array data (pulled from an XML file) in an HTML table format.
My array is setup as follows:
$strTodayIs = date('l F/n');
foreach($xml->last7days->day AS $Daily) {
//if (date('l F/n',(int)$Daily->starttime) != $strTodayIs) {
$intAverageLastweek += (int)$Daily->avgresponse;
$intDowntimeLast7 += (int)$Daily->totaldowntime;
$intUptimeLast7 += (int)$Daily->totaluptime;
array_push($arrLastWeek, array( "starttime" => $Daily->starttime,
"response" => $Daily->avgresponse,
"totalup" => $Daily->totaluptime,
"totaldown" => $Daily->totaldowntime
));
//}
}
I'm trying to display the results of some simple percentage calculations in an HTML table, using the data from the $arrLastWeek array.
My end goal is to display the background colour of each cell depending on the calculated value of the data from the array, e.g. 100 = green, 100 to 99.8 = yellow, less than 99.8 =red.
Again, any help even pointing me in the right direction would be greatly appreciated.
Please let me know if I've left out any important info that could help me solve my problem?
Regards,
Eli

Basically you're going to do something like this:
<?php foreach($array as $line): ?>
<tr><td><?php echo $line['value']; ?></td><td><?php echo $line['value2']; ?></td></tr>
<?php endforeach; ?>
You can do math by setting PHP variables to zero before the foreach, and adding to them inside the foreach, and outputting them somewhere.
Good luck

Related

How do you unserialize multiple strings of data with a loop?

Problem
I have a large csv file that I've exported from a mysql database. One of the file's columns has serialized strings in it. I'm trying to find a way to:
Unserialize each string (which lives in its own cell) of the column
Output it in a way so the text is in a similar format to this:
array (
'weight' => '108 lbs', 'ah' => '24"', 'sw' => '50"', 'sdw' => '23"', 'shw' => '18"', 'sd' => '27"', 'sh' => '12"',
)
Here is a sample of the unserialized rows (there are about 1000 of these):
a:7:{s:6:"weight";s:6:"30 lbs";s:2:"ah";s:3:"26"";s:2:"sw";s:3:"20"";s:3:"sdw";s:0:"";s:3:"shw";s:3:"19"";s:2:"sd";s:3:"19"";s:2:"sh";s:3:"17"";}
a:7:{s:6:"weight";s:7:"107 lbs";s:2:"ah";s:3:"26"";s:2:"sw";s:3:"72"";s:3:"sdw";s:3:"23"";s:3:"shw";s:3:"18"";s:2:"sd";s:3:"27"";s:2:"sh";s:3:"12"";}
a:7:{s:6:"weight";s:6:"37 lbs";s:2:"ah";s:0:"";s:2:"sw";s:0:"";s:3:"sdw";s:0:"";s:3:"shw";s:0:"";s:2:"sd";s:0:"";s:2:"sh";s:0:"";}
a:7:{s:6:"weight";s:6:"66 lbs";s:2:"ah";s:3:"26"";s:2:"sw";s:3:"50"";s:3:"sdw";s:3:"23"";s:3:"shw";s:3:"18"";s:2:"sd";s:3:"27"";s:2:"sh";s:3:"12"";}
a:7:{s:6:"weight";s:6:"30 lbs";s:2:"ah";s:0:"";s:2:"sw";s:3:"26"";s:3:"sdw";s:0:"";s:3:"shw";s:3:"18"";s:2:"sd";s:3:"39"";s:2:"sh";s:3:"12"";}
Questions
Is it possible to loop through serialized data, then unserialize it and display it in a desired format (e.g. in a HTML table format)?
Note: although this serialized data is from a MySQL database, if possible, I'd prefer not have to hook into the database to retrieve this serialized data again.
Attempted Solutions
So far, I have:
Reviewed the php documentation http://php.net/manual/en/function.unserialize.php
Review code examples on Stack Overflow
How to use php serialize() and unserialize()
How to get each value of unserialized data
Used tools like this http://unserialize.onlinephpfunctions.com/ to see how to use this function
Tried to implement my own code (see below)
After reading up on the topic/issue, I know I likely need to be using:
A loop (to loop through the serialized data)
var_export or var_dump to display the content in the desired format
Code Example
Here is the code I used to get the above result:
<?php
$var1='a:7{s:6:"weight";s:7:"105lbs";s:2:"ah";s:3:"23"";s:2:"sw";s:3:"26"";s:3:"sdw";s:0:"";s:3:"shw";s:3:"17"";s:2:"sd";s:3:"80"";s:2:"sh";s:3:"12"";}';
$var2='a:7:{s:6:"weight";s:7:"108 lbs";s:2:"ah";s:3:"24"";s:2:"sw";s:3:"50"";s:3:"sdw";s:3:"23"";s:3:"shw";s:3:"18"";s:2:"sd";s:3:"27"";s:2:"sh";s:3:"12"";}';
$combined = unserialize($var2);
$combined2 = unserialize($var1);
print_r($combined);
print_r($combined2);
?>
Although I'm not getting the desired output, I am able to get some unserialized data to appear on the screen:
Array ( [weight] => 108 lbs [ah] => 24" [sw] => 50" [sdw] => 23" [shw] => 18" [sd] => 27" [sh] => 12" ) Array ( [weight] => 105 lbs [ah] => 23" [sw] => 26" [sdw] => [shw] => 17" [sd] => 80" [sh] => 12" )
This is progress but it is problematic since it isn't a loop (was manually inputted) and is lacking HTML markup for easier formatting later on.
Any insight on this would be greatly appreciated. Thanks in advance!
UPDATE 1
Attempted Solutions
I created a temporary CSV file with only one column and 10 rows. See the CSV file here.
I've attempted to use the code #geoffry shared, but it doesn't seem to be pulling any info in from my csv file. I was getting an endless loop (1000's of <tr> tags showing up in the console (but with no content from the csv file).
After being pointed in the right direction with fgetscsv, I found the code below. With this code, I'm able to get the columns onto the page in their serialized form, so I know for sure the file is being opened properly. But this loop leaves out the unserialize step, which is more important here.
<?php
$filename = "myfilename.csv";
$id = fopen($filename, "r");
while ($data = fgetcsv($id, filesize($filename)))
$table[] = $data;
fclose($id);
echo "<table>\n";
foreach($table as $row)
{
echo "<tr>";
foreach($row as $data)
echo "<td>$data</td>";
echo "</tr>\n";
}
echo "</table>\n";
?>
I've tried combining aspects of this code and #geoffrey 's code below with no luck (for example, adding in the unserialize code to the loop).
Questions:
I read in the comments of the PHP fgetscsv manual that if you're a mac user (which I am), you need to add auto_detect_line_endings into your code. I've tried this and didn't notice any difference. Could this be part of the problem?
The placement of fclose($fp); in both #geoffrey 's code and the one I pasted above are different. Tried using it in different lines/areas of my code/loop without luck. Is this part of the reason why I'm not seeing anything when using unserialized in my code?
Anything I might be missing?
Thanks again for any insight. Much appreciated!
UPDATE 2
I was able to unserialize the serialized data using a helper function called maybe_unserialize. While I wasn't able to loop through all the code, it was a step in the right direction being able to get an unserialized array using PHP.
Code Example
<?php
$original = array(
'a:7:{s:6:"weight";s:7:"149 lbs";s:2:"ah";s:3:"24"";s:2:"sw";s:3:"75"";s:3:"sdw";s:3:"23"";s:3:"shw";s:3:"18"";s:2:"sd";s:3:"27"";s:2:"sh";s:3:"12"";}'
);
$string = implode(", ", $original);
$done = maybe_unserialize($string);
var_export($done);
?>
Hopefully this help anyone else with a similar issue!
Since you're dealing with a CSV I will assume that you would want to read in the file and iterate each row where the data you wish to unserialize is in column 5. I am also assuming the HTML output format desired, this should be enought to get you on your way.
<table>
<?PHP
$fp = fopen('file.csv', 'r');
while(($row = fgetcsv($fp)) !== false)
{
echo "<tr>";
$data = unserialize($row[5]);
foreach($data as $name => $value)
{
echo "<td>" . htmlspecialchars($name ) . "</td>";
echo "<td>" . htmlspecialchars($value) . "</td>";
}
echo "</tr>";
}
fclose($fp);
?>
</table>
You may want to check the documentation on fgetcsv as you may need to specify additional arguments depending on your CSV format.

Reading XML from eternal URL with either PHP or Jquery

I'm really stuck and would appreciate any advice. I have an XML document I want to be able to read but I can't get it to work with either Jquery or PHP. I have read multiple pages on online and tried everything including JSON encoding. I have read nearly a hundred tutorials online but everything I do doesn't seem to work. Is anybody able to write a script that can enable me to use some of the nodes in my document? The code below is the best I have been able to do so far. Is anybody able to make it so I can loop through the nodes etc?
To the person who marked this as a duplicate I have tried to look at those questions but I can't access the URL. I therefore can't compare the nodes/etc to see what I am doing wrong. I would really appreciate some help as I am quite new to this.
Thanks in advance for your help
<?php
$url = "https://developerdemo.isams.cloud/api/batch/1.0/xml.ashx?
apiKey=0A1C996B-8E74-4388-A3C4-8DA1E40ADA57";
$xml = simplexml_load_file($url);
$myJSON = json_encode($xml);
?>
<script>
var name='<?php echo $myJSON; ?>';
$.each(name, function(key, value) {
alert( "The key is '" + key + "' and the value is '" + value + "'" );
});
</script>
Once you have the code you already have it's simply a case of working with the XML structure, the following example loads the XML and then gives a list of the pupils (with a few details)...
$url = "https://developerdemo.isams.cloud/api/batch/1.0/xml.ashx?apiKey=0A1C996B-8E74-4388-A3C4-8DA1E40ADA57";
$xml = simplexml_load_file($url);
foreach ( $xml->PupilManager->CurrentPupils->Pupil as $pupil) {
echo $pupil['Id']." ".$pupil->SchoolCode." ".$pupil->Surname.PHP_EOL;
}
The id it puts out is the Id attribute of the Pupil element, the SchoolCode is the SchoolCode element in the Pupil.
The first few lines of output are...
1 101314800 Richards
3 PRE0000003SUF Thomas
5 PRE0000005SUF Davies
7 PRE0000007SUF Poole
What you can do is:
header('Content-Type: text/plain');
$resultArray = file_get_contents('path/to/file.xml');
$resultArray = (array)simplexml_load_string($resultArray);
The result will be an array of XML Objects and arrays, which you can access later via their property name or index respectively ($resultArray["foo"]->foo).

PHP JSON Parsing Issue

I have this JSON output from a Government API, I need to display it using PHP. The problem is I can't use foreach more then once in a row or it doesn't work. I can't load all the criteria into the first foreach because say the first piece of data ACASS returns 3 results, all the fields after it will be displayed 3 times. Each field could return 1-10 results so there needs to be a system that accounts for variables.
I'm thinking the solution is to put all of the JSON items I need displayed into the first foreach but set them to only display if they're populated. That or use the current coding system I have but account for variable numbers somehow.
Any potential solutions are greatly appreciated.
This is the JSON output... https://api.data.gov/sam/v4/registrations/9606040070000?api_key=WI7nHENlp6QDMnWsb0Nnmzsv1slPDTjNM0XBoKvY
Here's the PHP I'm using...
echo "ACASS ID:".$decoded_results['sam_data']['registration']['qualifications']['acass']['id']."</br>";
foreach($decoded_results['sam_data']['registration']['qualifications']['acass']['answers'] as $acass)
{
echo 'Answer Text:'.$acass['answerText'].'</br>';
echo 'ACASS Section:'.$acass['section'].'</br>';
}
$formerfirm = $decoded_results['sam_data']['registration']['qualifications']['acass']['answers'][2]['FormerFirm'];
echo 'Former Firm ID:'.$formerfirm['id'].'</br>';
echo 'Former Firm Year Established:'.$formerfirm['yearEstablished'].'</br>';
echo 'Former Firm Name:'.$formerfirm['name'].'</br>';
echo 'Former Firm DUNS'.$formerfirm['duns'].'</br>';
I did my best to keep this short and simple question / code wise. In summary the issue is if you look at the JSON the data hierarchy makes a lot of the information display under ACASS/Answers and then the next category. I never know how many responses there will be and I'm not sure how to account for those variables.
I would like to thank everyone on these boards who has guided me as a new member and helped me post cleaner, more concise questions. Also thank you to everyone who has taken their own personal time to help me learn to become a better programmer.
use a tool like http://jsonviewer.stack.hu/ for visualizing your json structure. It helps a lot.
<?php
$url = "https://api.data.gov/sam/v4/registrations/9606040070000?api_key=WI7nHENlp6QDMnWsb0Nnmzsv1slPDTjNM0XBoKvY";
$contents = json_decode(file_get_contents($url));
// echo var_dump($contents);
$sam_data = $contents->sam_data;
// echo var_dump($sam_data);
$registration = $sam_data->registration;
//echo var_dump($registration);
$acass = $contents->sam_data->registration->qualifications->acass;
$id = $acass->id;
echo "id: ". $id . "<br />";
//echo var_dump($acass->answers);
foreach($acass->answers as $answer) {
if(isset($answer->FormerFirm)) {
$formerFirm = $answer->FormerFirm;
echo var_dump($formerFirm);
}
}

PHP/MySQL - How to adjust query based on the length (characters) within database

I've had excellent support here, so I figured I'd try again, as I have no clue where to even begin looking for this answer.
I have a simple MySQL database, named "testimonials", which contains 3 tables, "id", "name", "content"
What I want to do, is display testimonials within a fixed size block. Just simply displaying the content is no problem at all, however where I'm stuck is the (somewhat) unique way I'm trying to make it work. I would like to display a random item on each page load, and then to check the character length of the "content" within the testimonial, and if it's equal to or greater than XX length, then just display the one testimonial, otherwise if it's less than XX in length to display a second testimonial (assuming it combined with the first doesn't break the container box).
The box in question is 362px in width and 353px in height using 14px font with Verdana. An example of how the testimonial will appear on the page is like this:
"This is the testimonial content, some nice message from a client."
-- Billy Bob, Owner, Crazy Joe's Tavern
The "name" table in the database holds everything in bold (minus the -- of course), in case someone felt the need to ask.
As I typed that, I felt as if I was asking for a miracle, however I'll still post the question, hoping someone might just know the answer. As always, thanks for any help I may get, if this is just simply asking too much, I'm not totally against the idea of only displaying one testimonial at a time making a ground rule saying they have to contain a minimum of XX characters.
Thanks!
Quick Update: I didn't expect to get answers so quickly, I'm not at my desk at the moment, so as soon as I sit back down I'll go through and see which answer fits best. However, do you guys get together and try to make your answer more complex than the previous answer? lol, thanks though, for anyone who's offering help, you guys rock!
Final edit: I decided against this whole idea, as it just way over complicated everything. For the time being, I'm just going to display all testimonials, and make them scroll, while I work on a jQuery snippet to make it prettier. Thanks everyone for your help though! Should I decide again to do this, I'll be trying my chosen answer.
You just need a loop. Pseudo-code:
$length = 0;
$target = 200; // or whatever
while( $length < $target ) {
$comment = getOneComment();
displayComment($comment);
$length += strlen( $comment['content'] ); // assuming getOneComment() returns an associative array
}
To make it pretty, if the display box is going to a be a fixed height, you could use some jQuery to toggle whether to show the second comment on not.
Assuming you have testimonials in an array:
$testimonials = array(
't1' => array(
'content' => 'testimonials 1 content..',
'author' => 'the author'
),
't2' => array(
'content' => 'testimonials 2 content..',
'author' => 'the author 2'
),
);
You could have an maxLengthTestimonialsContent and maxLenthAllTestimonnials variable :
$maxLengthTestimonialsContent = 120;
$maxLenthAllTestimonnials = 240;
And now with a simple loop you build the array testimonials that you will use to show:
$testimonialsToShow = array();
$i = 1; $totalLength = 0
foreach($testimonials as $t) {
if( $i > 1 && strlen( $t['content']) < $maxLengthTestimonialsContent
&& $totalLength < $maxLenthAllTestimonnials )
break; // basically here you test that testimonials less first
// and with less length than maxLengthTestimonial, and also
// total length less than maxLengthAll to be stored
//in $testimonialsToShow
else {
$testimonialsToShow[] = $t;
$totalLength = $t['content'];
}
}
Something like this is what you would need.
<?php
$str = $res["testimonial"];
if (strlen($str) > 50) {
// Logic to retrieve and display second testimonial
}
?>
Obviously there's some more processing you'll have to come up with to determine if the second testimonial is short enough to fit or not. But that should get you started.
EDIT:
For the randomization, I use this on my own site:
$referrals = mysql_query("SELECT id FROM ts_testimonials");
$referralView = array();
$i = 0;
while ($newReferral = mysql_fetch_array($referrals)) {
$referralView[$i] = $newReferral['id'];
$i++;
}
if (sizeof($referralView) >= 1){
$referralTop = rand(0,sizeof($referralView)-1);
$newReferralTop = mysql_fetch_array(mysql_query("SELECT * FROM ts_testimonials WHERE id = '".$referralView[$referralTop]."'"));
if (sizeof($referralView) >=2){
$referralBottom = rand(0,sizeof($referralView)-1);
while ($referralBottom == $referralTop) {
$referralBottom = rand(0,sizeof($referralView)-1);
}
$newReferralBottom = mysql_fetch_array(mysql_query("SELECT * FROM ts_testimonials WHERE id = '".$referralView[$referralBottom]."'"));
}
}

How to randomly select a video and play?

Im learning JQuery and php.
Is it possible to store multiple video links within variables and get php to echo one at random??
My goal is to control my own video ads on my site and I thought this would be a good idea but I dont have a clue where I should look online.
Here is what I was thinking
<?php
$advert1 = 'MyVIDEO1.mp4';
$advert2 = 'MyVideo2.mp4';
$advert3 = 'MyVideo3.mp4';
I want a code that would go here and say: randomly select one of these vars.
echo "At random one of the vars";
?>
I hope Im making sense. help?
You could make an array, like this:
$advert[] = array();
$advert[1] = 'MyVIDEO1.mp4';
$advert[2] = 'MyVIDEO2.mp4';
$advert[3] = 'MyVIDEO3.mp4';
$chosen_one = rand(1,count($advert));
echo $advert[$chosen_one];
You can also use array_rand() instead of shuffle():
<?php
$videos = array("MyVIDEO1.mp4", "MyVideo2.mp4", "MyVideo3.mp4");
echo $videos[array_rand($videos)];
?>
For embedding the video in the right way, have a look at http://www.w3schools.com/html/html_videos.asp
For a start, PHP itself won't exactly play a video. You could use it to echo out one of the URL's to a video. So, bear in mind there is a lot more to do than just select a video.
To answer your question in the code I'd recommend the following:
Try looking up PHP arrays. You want to keep all the videos in an array.
Next up, you'll want to shuffle that array. Then select the first element.
$videos = array("MyVIDEO1.mp4", "MyVideo2.mp4", "MyVideo3.mp4");
shuffle($videos);
echo $videos[0];
This is a simple solution
Place your adverts in an array
<?php
$adverts = array("advert1" => "MyVIDEO1.mp4",
"advert2" => "MyVIDEO2.mp4",
"advert3" => "MyVIDEO3.mp4");
$count = count($adverts);
$rand_advert = rand(1, $count);
echo $adverts['advert'.$rand_advert];
?>
Or alternatively if you don't want to have keys and just put the values in the array straight away
<?php
$adverts = array("MyVIDEO1.mp4",
"MyVIDEO2.mp4",
"MyVIDEO3.mp4");
shuffle($adverts);
echo $adverts[0];
?>
You have need all value in a array then find index randomly and show it.
<?php
$advert = array(
'MyVIDEO1.mp4',
'MyVideo2.mp4',
'MyVideo3.mp4'
);
$total_video = count($advert);
$total_video--; //array index starting from 0 so decrease 1
$random_index = rand(0, $total_video); //array index 0 to 2
$video_to_play = $advert[$random_index];
echo $video_to_play;
?>

Categories