I have a file with 20 pictures of country artists, and a text file with their websites. I'm trying to display this data in a 4 row 5 column table using PHP.
I try to use a foreach loop that iterates for every 5 elements in the array
(to load each row one by one)
foreach(array_chunk($CountryArtists, 5, true) as $Value) {
<table>
<tr><td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td></tr>
</table>
Ive been trying to figure out how to load the images into the array, but having no luck. Im starting to think i must put the reference to the file location in the array,but i am not sure.
$colsToDisplay = 5;
$CountryArtists = array("C:\Users\THEFOLDER\images");
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", RTravis", "STwain", TKeith", TMcgraw");
$filename = "C:\Users\THEFOLDER\images";
I'm relatively new to PHP and really just need to know how to load my images and how to make this table show up correctly.
EDIT:
I added echo to the table lines but it just shows echo in the browser output:
" echo " $CountryArtists[$Value] $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo "" } ?>
My code now looks like this:
foreach(array_chunk($CountryArtists, 5, true) as $Value) {
echo "<table>"
echo "<tr><td> $CountryArtists[$Value] $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td></tr>"
echo "</table>"
}
I feel like I'm doing strong wrong, would be so grateful to have it pointed out to me.
FULL FILE
<!DOCTYPE HTML>
<html>
<body>
<?php
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", "RTravis", "STwain", "TKeith", "TMcgraw");
$count = count($ArtistImages);
$cols = 6;
$div = (int) $count / (int)$cols;
$diff = ceil($div);
echo
$fin = $cols * $diff;
$a = 1;
echo '<table>';
for($i = 0; $i < $fin; $i++) {
if($a == 1)
echo "\t<tr>".PHP_EOL;
$artist = (!empty($ArtistImages[$i]))? $ArtistImages[$i]: "";
echo "\t\t".'<td>'.$artist.'</td>'.PHP_EOL;
if($a == $cols) {
echo "\t</tr>".PHP_EOL;
$a=0;
}
$a++;
}
echo '</table>';
?>
</body>
</html>
I think you may be looking for something similar to this algorithm. It adds a row every 5 values. You will want to do a divisor make it ceil() to make it add any required empty cells. You can do this foreach if you do <ul> and <li> and use CSS to make them display like a table. Then you don't need to calculate extra cells.
$i = 1;
echo '<table>';
foreach($array as $value) {
if($i == 1)
echo "<tr>";
echo '<td>'.$value.'</td>';
if($i == 5) {
echo "</tr>";
$i=0;
}
$i++;
}
echo '</table>';
EDIT:
Here is a more practical version based on yours:
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", "RTravis", "STwain", "TKeith", "TMcgraw");
// Count total artists in array
$count = count($ArtistImages);
// Choose how many to display per row
$cols = 6;
// Divide the total by the columns
$div = (int) $count / (int)$cols;
// Round up (incase the number will produce empty cells
$diff = ceil($div);
// Mulitply the final numbers
$fin = $cols * $diff;
// Create an autoincrementer to keep track of next rows
$a = 1;
echo '<table>'.PHP_EOL;
for($i = 0; $i < $fin; $i++) {
if($a == 1)
echo "\t<tr>".PHP_EOL;
// You need to see if this artist is populated. If not, make empty
// If left without this it will have a warning saying not exists
$artist = (!empty($ArtistImages[$i]))? $ArtistImages[$i]: "";
echo "\t\t".'<td>'.$artist.'</td>'.PHP_EOL;
if($a == $cols) {
echo "\t</tr>".PHP_EOL;
$a=0;
}
$a++;
}
echo '</table>';
In the php file you need to echo the data you want.
However if you in the php file you can close php like this.
? >
And write html code.
When you want to display php attributes you again need to open a php like this:
and continue like this...
Php fcan only return string or json data
Let me know if it work for you....
Related
I am newer to PHP and I am able to get the desired output but I am doing it one index position at a time. I am returning data from a .txt file and I need to insert this data into an HTML table I am creating using PHP. BUT FIRST I need to be able to get the same output without typing out every index position. I tried to use a forloop but it kept outputting only one line.
I manually outputted the lines from the file and it works. What loop in PHP would be best to achieve the same results and output these elements? IMPORTANT, as is I am able to sort and rsort (I want to be able to do this so if it can be implemented in the loop that would be awesome) any help is more than I have right now.
PHP
$books = array();
if ($fp)
{
while(true)
{
$lines_in_file = count(file($filename));
$line = fgets($fp);
if (feof($fp))
{
break;
}
$line_ctr++;
list($title, $author, $pubdate, $isbn) = explode('*', $line);
$new_line = explode('*', $line);
for($ii= 1; $ii <= $lines_in_file; $ii++){
$lines = fgets($fp); //Read each line
$member = trim($lines);
array_push($books, $member);
}
//This foreach only brings back the first like in the txt file, why?
$cntr = 0;
foreach($books as $element){
$cntr++;
$table .= "<tr>";
$table .= "<td>".$title."</td>";
$table .= "<td>".$author."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$isbn."</td>";
$table .= "</tr>\n"; //added newline
echo $element;
}
//sort($books);
// rsort($books);
echo $books[0];
echo "<br>";
echo $books[1];
echo "<br>";
echo $books[2];
echo "<br>";
echo $books[3];
echo "<br>";
echo $books[4];
echo "<br>";
echo $books[5];
echo "<br>";
echo $books[6];
echo "<br>";
echo $books[7];
echo "<br>";
echo $books[8];
echo "<br>";
echo $books[9];
echo "<br>";
echo $books[10];
echo "<br>";
echo $books[11];
echo "<br>";
echo $books[12];
echo "<br>";
echo $books[13];
echo "<br>";
echo $books[14];
echo "<br>";
echo $books[15];
echo "<br>";
echo $books[16];
echo "<br>";
echo $books[17];
}//END WHILE LOOP
fclose($fp ); //Close file
}
Having to make a few guesses here but i believe the file is going to look like:
title*author*pubdate*isbn
title*author*pubdate*isbn
title*author*pubdate*isb
if this is wrong, let me know
as long as the fie is not to large read it in to an array:
$book_array=file('book_file.txt');
//print_r($book_array); //is it an array of the books, one book per array key
now to separate each line:
foreach($book_array as $line){
$line_sep=explode('*',$line);
// with no sorting option you could just echo inside the loop
//if you want to keep sorting options we have to keep the separated lines
$new_book_array[]=$line_sep;
}
unset($book_array);//free up memory if needed
//print_r($new_book_array);//is it a multi-d array, book then the 4 elements
to sort our new multidimensoanl array:
usort($new_book_array, function($a, $b) {
return strcmp($a['0'], $b['0']);;
}); //this sorts on key 0 in your case title:
//print_r($new_book_array); // has it sorted properly
for display:
loop again
echo '<table><tr><th>Title</th><th>Author</th><th>Pub Date</th><th>ISBN</th></tr>';
foreach($new_book_array as $book){
//print_r($book); //is it each indervidual book array with 4 elements
echo '<tr><td>'.$book[0].'</td><td>'.$book[1].'</td><td>'.$book[2].'</td><td>'.$book[3].'</td></tr>';
}
echo '</table>';
I'm trying to make a php slideshow and I'm almost done I just need to implement the next and back buttons which I thought were going to be easy, but apparently you can't increment indexes in php?
$sql = "SELECT pic_url FROM pic_info";
$result = $conn->query($sql);
$count = 0;
$dir = "http://dev2.matrix.msu.edu/~matrix.training/Holmberg_Dane/";
$source = "gallery.php";
if ($result->num_rows > 0) {
// output data of each row
$pic_array = array();
while ($row = $result->fetch_assoc()) {
$pic_array[$count] = $row['pic_url'];
$count++;
}
$index = 1;
echo "<img src= ' $dir$pic_array[$index]' />";
echo "<a href= '$dir$pic_array[$index + 1]'>next</a>";
echo "<a href= '$dir$pic_array[$index - 1]'>back</a>";
}
$conn->close();
?>
Try this
<?php
echo '<img src="'.$dir.$pic_array[$index].'">
next
back';
?>
I would suggest to place the url's in an array and loop over them.
$urls = ['website/url/for/image/image.jpg', 'another/url/image.jpg'];
foreach ($urls as $url) {
echo 'a href="http://'.$url.'"> Click </a>';
}
It is definitely more readable that way.
I have a section of php code where I need for the $_POST index to increment by one each time it goes through the "do while" loop. In other words, the first occurrence would be $_POST['tableserver1'], then the next one would be $_POST['tableserver2'], etc. This loops 6 times and then stops.
I have tried using variables as the index, trying to get them to increment. I found an example in the php manual http://php.net/manual/en/language.operators.increment.php which increments the number at the end of a string, but I'm not having any luck with getting it to work inside the $_POST index.
This section of code creates a set of 6 select lists that contain names from the database. I am trying to get the select lists to populate from the $_POST value if it is set, other wise it is zero.
Here is my code:
<?php
$x = 1;
do {
?>
<blockquote>
<p><?php echo $x . "."; ?>
<select name="tableserver<?php echo $x; ?>" id="tableserver<?php echo $x; ?>">
<option selected value="0" <?php
if (!(strcmp(0, '$tableserver.$x'))) {
echo "selected=\"selected\"";
}
?>>Select Server</option>
<?php
do {
if (strpos($row_getnamesRS['service'], '22') !== false) {
?>
<option value="<?php echo $row_getnamesRS['memberID'] ?>" <?php
if (!(strcmp($row_getnamesRS['memberID'], '$tableserver.$x'))) {
echo "selected=\"selected\"";
}
?>><?php
echo ucfirst(strtolower($row_getnamesRS['first_name']))
. " " . ucfirst(strtolower($row_getnamesRS['last_name']))
?></option>
<?php
}
} while ($row_getnamesRS = mysqli_fetch_assoc($getnamesRS));
$rows = mysqli_num_rows($getnamesRS);
if ($rows > 0) {
mysqli_data_seek($getnamesRS, 0);
$row_getnamesRS = mysqli_fetch_assoc($getnamesRS);
}
?>
</select>
</p>
</blockquote>
<?php
$x++;
} while ($x <= 6);
?>
$i=0;
do{
echo $_POST['someval'.$i];
}while(++$i < 6)
Perhaps like this? ...
$arr = [];
for ($i = 1; $i <= 6; $i++)
array_push($arr, $_POST["tableserver" . $i]);
$arr; // Contains 6 values (starting from $_POST["tableserver1"] to $_POST["tableserver6"])
It would be easier to post an an array
so instead of
name="tableserver<?php echo $x; ?>"
use
name="tableserver[]";
the you can just do
foreach($_POST['tableserver'] as $tableServer){....}
I am trying to create a PHP function that will echo info from a db. My col names look like banana[1], banana[2], apple[1], apple[2], apple[3], and so on.
The function will select the fruit
function fruits($fruit){
}
and then within that function I'll loop through the fruits.
How do I echo these?
echo $fruit[$i];
obviously doesn't work.
Pretty basic, but I can't figure out. Concatenation kills me.
function ponctuation($section,$sect){
switch($section){
case 'apple':
$i=1;
break;
case 'banana':
$i=13;
break;
}
global $mysql_tablename;
global $FName;
global $Lname;
if(isset($mysql_tablename)){
$result = mysql_query("SELECT * FROM $mysql_tablename WHERE FName='$FName' AND Lname='$Lname'");
$row = mysql_fetch_array($result);
echo '<form method="post" action="ponctuation.php?'.${$section.$sect}.'_valider">';
echo '<ul>';
$query = mysql_query("SELECT * FROM `ponct_enonces` WHERE `section`='$section' AND `sect`='$sect'");
while($row_q = mysql_fetch_assoc($query)) {
if($row_q['enon']==0 && $row_q['senon']==0){
echo '<h2>'.$row_q['enonce'].'</h2>';
}
if($row_q['enon']==1){
echo '<h3>'.$row_q['enonce'].'</h3>';
echo '<textarea rows="3" cols="100" name="'.$i.'" wrap="physical">' . $row[$section[$i]] . '</textarea>';
}
if($row_q['senon']==1){
echo '<h4>'.$row_q['enonce'].'</h4>';
echo '<textarea rows="3" cols="100" name="'.$i.'" wrap="physical">' . $row[$section]. '</textarea>';
}
$i++;
}
echo '</ol>';
echo '<input type="submit" name="submit" value="Valider"/>';
echo '</form>';
}
}
The code is a little ugly, and some vars have French names, other have English names.
col names won't be expanded into PHP array structures for you, e.g.
SELECT fruit[1], fruit[2], ...., fruit[100]
will give you the equivalent of
$row = array(
'fruit[1]' => someval,
'fruit[2]' => someval,
...
);
if you want to iterate those, you'll have to get ugly:
$fruit = array();
for ($i = 0; $i <= 100; $i++) {
$fruit[$i] = $row['fruit[' . $i . ']'];
}
which begs the question of... why? This is a horrible data structure to be using. Properly normalizing it into a 'fruit attributes' sub-table would save you this trouble, and also allow you to have n attributes, rather than the fixed 1..100 range or whatever it is you have.
If you're attempting to loop over all the columns in a row, you can use fetch_array:
$result = $mysqli->query($query);
$row = $result->fetch_array();
// loop over columns
for ($i = 0, $count = count($row); $i < $count; $i++)
echo $row[$i];
That way, you won't have to worry about the column names. I might be misunderstanding your question, though.
I am creating an in-house order pulling application. I'm pulling form an ODBC source and placing items in an array. I'm then creating a new flat file for each order being physically worked on. When the user scans/enters an item from that order number it places that item on a new line in the order file that was created.
I'm then reading that order file back to get the items that have been scanned thus far. Where I'm stuck is how to mark that line item that exist in the order file as being completed in the HTML table.
Here is the pertinent code as it relates to my question:
$file_array = file_get_contents($file_ordnumber, "rb");
$items_array = explode("\n",$file_array);
echo "<table>";
for ($i = 0; $i < count($location_array); $i++)
{
echo "<tr>";
if (in_array("$itemno_array[$i]", $items_array)) {
echo "<td>$itemno_array[$i] EXISTS</td>";
}
else {
echo "<td>$itemno_array[$i] NO EXIST</td>";
}
// echo "<td>$location_array[$i]</td>";
echo "<td>$qty_array[$i]";
echo "<td>$pickingseq_array[$i]</td>";
echo "</tr>";
}
echo "</table>";
As you can see I'm iterating through the array and displaying it in a HTML table. I'm curious why my above code isn't working. My result ends up being from the 'else' statement thus ALL lines, even if they exist in the file is showing as "NO EXIST" which is obviously incorrect.
Can you post your Print_r($items_arr);
also try using isset($arrayVar[$key]
and try removing double quotes and see if it works.. like ...
$file_array = file_get_contents($file_ordnumber, "rb");
$items_array = explode("\n",$file_array);
echo "<table>";
for ($i = 0; $i < count($location_array); $i++)
{
echo "<tr>";
if (in_array($itemno_array[$i], $items_array)) {
echo "<td>".$itemno_array[$i]." EXISTS</td>";
}
else {
echo "<td>".$itemno_array[$i]." NO EXIST</td>";
}
// echo "<td>".$location_array[$i]."</td>";
echo "<td>".$qty_array[$i]."";
echo "<td>".$pickingseq_array[$i]."</td>";
echo "</tr>";
}
echo "</table>";
I got this resolved by going about it a different way. I use strpos() to search the flat file itself rather than the array that I exploded from it:
echo "<table>";
//for ($i = 0; $i < count($itemno_array); $i++)
for($i=0;$i<sizeof($itemno_array);$i++)
{
echo "<tr>";
// if (in_array($itemno_array[$i], $items_array)) {
echo "<td>";
$var = $itemno_array[$i];
$newvar = trim($var);
if(strpos($file_array, $newvar ) !==FALSE) {
echo "$var ** EXISTS</td>";
}
else {
echo "$var DOES NOT EXIST **</td>";
}
// echo "<td>$location_array[$i]</td>";
echo "<td>$qty_array[$i]";
echo "<td>$pickingseq_array[$i]</td>";
echo "</tr>";
}
echo "</table>";