How to get value from next iteration of foreach loop - php

I'm trying to print out entries from a SQL database. Some of the entries are images, and I want to parse those and put them in appropriate HTML markup.
Database Example
id | datatype | typetext
78 | paragraph | "hello"
79 | image | "image.jpg"
80 | paragraph | "goodbye"
The column datatype signifies what type of data is being stored in a given row, and I want to catch when the value of datatype is "image" - then jump to the following typetext column and prepare the appropriate markup for this image.
For instance, some psuedo-code of what I'm trying to do:
if(column is datatype){
if(datatype == 'image'){
echo '<p>' . data inside accompanying typetext column . '</p>';
}
}
Here's my current code:
//the array of the blog entry
foreach($entry as $key => $entryUnit){
//the array of the entry unit
foreach($entryUnit as $column => $cell){
if($column == 'datatype'){
if($key == 'image'){
echo '<br/>';
echo '<p style="color: pink;">' $cell . $entryUnit[$column + 1] . '</p>';
echo '<br/>';
}
}
else if($column == 'typetext'){
echo '<br/>';
echo $cell;
echo '<br/>';
}
}
}
In the first if statement, I try jumping to the next column with echo '<p style="color: pink;">' $cell . $entryUnit[$column + 1] . '</p>';, but this doesn't work.
I've also tried utilizing the next() function, like:
echo '<p>' . next($cell) . '</p>';`
..but this also doesn't work as I thought it would.

You don't need that nested foreach loops, you can everything in just one simple foreach loop.
foreach($entry as $entryUnit){
if($entryUnit['datatype'] == "image"){
echo '<br/>';
echo '<p style="color: pink;">' . $entryUnit['typetext'] . '</p>';
echo '<br/>';
}elseif($entryUnit['datatype'] == "paragraph"){
echo '<br/>';
echo $entryUnit['typetext'];
echo '<br/>';
}
}

Somethink like this should work:
//the array of the blog entry
foreach($entry as $key => $entryUnit){
$i=0;
//the array of the entry unit
foreach($entryUnit as $column => $cell){
if($column == 'datatype'){
if($key == 'image'){
$i++;
echo '<br/>';
echo '<p style="color: pink;">' $cell . $entryUnit[$i] . '</p>';
echo '<br/>';
}
}
else if($column == 'typetext'){
echo '<br/>';
echo $cell;
echo '<br/>';
}
}
}

Related

PHP Json values with a specified label

I am using json_decode and echoing the values using a nested foreach loop.
Here's a truncated json that I am working on:
[{"product_name":"Product 1","product_quantity":"1","product_price":"2.99"},....
and the loop
foreach($list_array as $p){
foreach($p as $key=>$value) {
$result_html .= $key.": ".$value."<br />";
}
}
This was I am able to echo all key/value pairs.
I have tried using this to echo individual items something like:
foreach($list_array as $p){
foreach($p as $key=>$value) {
echo "Product: ".$p[$key]['product_name'];
echo "Quantity: ".$p[$key]['product_quantity'];
}
}
However I am unable to because it doesn't echo anything.
I would like to be able to show something like:
Product Name: Apple
Quantity: 7
Currently it is showing:
product_name: Apple
product_quantity: 7
How can I remove the key and replace it with a predefined label.
It can be done with:
foreach ($list_array as $p){
$result_html .= 'Product: ' . $p->product_name
. 'Quantity: ' . $p->product_quantity . '<br />';
}
If you are decoding your json into an object you can do it like that.
$list_array = json_decode('[{"product_name":"Product 1","product_quantity":"1","product_price":"2.99"}]');
$result_html = '';
foreach($list_array as $p){
$result_html .= '<div>Product: '.$p->product_name.'</div>';
$result_html .= '<div>Quantity: '.$p->product_quantity.'</div>';
}
echo $result_html;

Extracting columns from sql table with php

My query selects all columns from my table
$spool = $wpdb->get_results('SELECT * FROM `tablename`');
then I display the results in a table. I need to display all columns. This is the way I do it.
echo "<table>";
if ( !empty( $spool ) ) {
echo "<tr><th> header </th></tr>";
foreach ( $spool as $a ) {
echo "<tr><th>" . $a->columnname1 . "</th><th>" .$a->columnnameN . "</th></tr>";
}
}
echo "</table>";
Now since I have around 40 columns, I'd like to ask if there is a more intelligent and less tedious way of displaying them.
probably you need nested loops, you are getting result probably like this
array(
0:{column1:test,column2:test . . . },
1:{column1:test,column2:test . . . }
)
so you can try this way
echo "<table>";
if ( !empty( $spool ) ) {
echo "<tr><th> header </th></tr>";
foreach ( $spool as $key => $value ) {
echo '<tr>';
foreach ( $value as $a ) {
echo "<th>" . $a. "</th>";
}
echo '</tr>';
}
}
echo "</table>";
As you have objects you could cast them to arrays and use implode.
(But attribute order could be different from what you want.)
<?php
class A
{
public $foo = 'bing';
public $bar = 'bang';
public $baz = 'bong';
}
$spool = [new A, new A];
echo '<table>';
foreach($spool as $a) {
echo '<tr>';
echo '<td>' . implode('</td><td>', (array) $a) . '</td>';
echo '</tr>';
}
echo '</table>';
Output:
<table><tr><td>bing</td><td>bang</td><td>bong</td></tr><tr><td>bing</td><td>bang</td><td>bong</td></tr></table>

Formatting PHP explode array into HTML

We have a client who wants to output cinema listings on their website. This particular cinema has provided us with a link to retrieve the information from. This link is simply outputted in plain text, with the elements seperated by ~|~
I am using explode and strpos to divide the listings into divs however it still isn't good enough for what I am wanting to achieve. I just can't get my head around what I can do to format this correctly. This is my code:
<?php
$theArray = explode("~|~", file_get_contents("THE URL"));
echo "<ul id=\"cinemaListings\">";
foreach($theArray as $item){
$findcinemaid = '~77';
$findcinemaname = 'Cinema Name';
$findx = 'X';
$findu = 'U';
$findgen = 'Gen';
$findlink = '.ie';
if(strpos($item, $findcinemaname) !== false){
echo "<div class='cinemaName'>" . $item . "</div>";
}elseif(strpos($item, $findgen) !== false){
echo "<div class='cinemaGen'>" . $item . "</div>";
}elseif(strpos($item, $findcinemaid) !== false){
echo "<li>";
}elseif($item == $findx){
echo "<div class='cinemaX'>" . $item . "</div>";
}elseif(strlen($item) == 8){
echo "<div class='cinemaCode'>" . $item . "</div>";
}elseif(strlen($item) == 3){
echo "<div class='cinemaListId'>" . $item . "</div>";
}elseif(strlen($item) == 2){
echo "<div class='cinemaListId'>" . $item . "</div>";
}elseif(strlen($item) == 1){
echo "<div class='cinemaListId'>" . $item . "</div>";
}elseif(DateTime::createFromFormat('H:i', $item) !== FALSE){;
echo "<div class='cinemaTime'>" . $item . "</div>";
}elseif(strpos($item, $findlink) !== false){
echo "<div class='cinemaLink'>" . $item . "</div>";
}elseif(DateTime::createFromFormat('d/m/Y', $item) !== FALSE){;
echo "<div class='cinemaDate'>" . $item . "</div>";
}else {
echo "<div>" . $item . "</div>";
}
}
echo "</ul>";
?>
This script however is outputting (with divs and classes of course, just don't want to add them all):
<li>The Smurfs 2 2D 30/08/2013 11:10</li>
<li>The Smurfs 2 2D 30/08/2013 13:20</li>
<li>The Smurfs 2 2D 31/08/2013 11:10</li>
<li>The Smurfs 2 2D 31/08/2013 13:20</li>
<li>Elysium 04/09/2013 15:45</li>
<li>Elysium 04/09/2013 21:00</li>
<li>Elysium 05/09/2013 15:45</li>
Is there any possible way to format it as follows:
<li>
The Smurfs 2 2D
30/08/2013 (today's date)
11:10 13:20
</li>
<li>
Elysium
04/09/2013 (today's date)
15:45 21:00
</li>
So just one film name, todays date and the times for that day (with classes ofcourse). Then onto the next film... etc.
I'm stuck and would appreciate any help! Thanks in advance.
Are you talking about the source layout or the front end html layout? If it's the source layout, have you tried replacing this:
echo "<div class='cinemaName'>" . $item . "</div>";
With this(?):
echo "<div class='cinemaName'>" . preg_replace( ' ', "\r\n", $item ) . "</div>";
Since it looks like there are 3 spaces between each segment of the $item, you can replace them with return shorthand \r\n (or just \n for some systems).
If it's the front end layout, just use the same method, but instead of \r\n, change it to <br/>.

Echo selective data (rows) from multidimensional array in PHP

I have an array coming from a .csv file. These are coming from a real estate program. In the second column I have the words For Sale and in the third column the words For Rent that are indicated only on the rows that are concerned. Otherwise the cell is empty. I want to display a list rows only For Sale for example. Of course then if the user clicks on a link in one of the rows, the appropriate page will be displayed.
I can't seem to target the text in the column, and I can't permit that the words For Sale be used throughout the entire array because they could appear in another column (description for example).
I have tried this, but to no avail.
/* The array is $arrCSV */
foreach($arrCSV as $book) {
if($book[1] === For Sale) {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
I also tried this:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
Do you mean:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div></div>';
}else{
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
}
I found a solution here:
PHP: Taking Array (CSV) And Intelligently Returning Information
$searchCity = 'For Sale'; //or whatever you are looking for
$file = file_get_contents('annonces.csv');
$results = array();
$lines = explode("\n",$file);
//use any line delim as the 1st param,
//im deciding on \n but idk how your file is encoded
foreach($lines as $line){
//split the line
$col = explode(";",$line);
//and you know city is the 3rd element
if(trim($col[1]) == $searchCity){
$results[] = $col;
}
}
And then:
foreach($results as $Rockband)
{
echo "<tr>";
foreach($Rockband as $item)
{
echo "<td>$item</td>";
}
echo "</tr>";
}
As you can see I'm learning. It turns out that by formulating a question, a series of similar posts are displayed, which is much quicker and easier than using google. Thanks.

Help me combine these conditions for determining if this list item begins with a new letter

Maybe I'm having a bad day, but I can't seem to combine these 2 conditions into 1. They obviously should be, because they output the exact same data. The following code creates a list with A-Z to act as anchor links, and is then meant to traverse an array in the format 'word'=>'definition'. I wanted the PHP to output a h3 element with the current letter everytime it detected a new letter.
Here is what I have
$letters = range('A', 'Z');
echo '<em>Jump to:</em><ul class="letters">';
// anchors
foreach ($letters as $letter) {
echo '<li>' . $letter . '</li>';
}
echo '</ul>';
// start listing them!
$currentLetter = 0;
echo '<dl id="botany-words">';
foreach($content as $botanyWord=>$definition) {
if ($botanyWord == key(array_slice($content, 0, 1))) { // must be first, aka 'A'
echo '<h3 id="botany-words-' . $letters[$currentLetter] . '">' . $letters[$currentLetter] . '</h3>';
}
if (substr($botanyWord, 0, 1) != $letters[$currentLetter]) { // if the first character of this botany word is different to the last
echo '<h3 id="botany-words-' . $letters[$currentLetter] . '">' . $letters[$currentLetter] . '</h3>';
$currentLetter++;
}
?>
<dt><?php echo $botanyWord; ?></dt>
<dd><?php // echo $definition; ?></dd>
<?
}
echo '</dl>';
Everytime I tried to do
if ($botanyWord == key(array_slice($content, 0, 1)) || substr($botanyWord, 0, 1) != $letters[$currentLetter])
it didn't work right, and error'd because it overflowed the 26th index (obviously being 26 chars in the alphabet).
Thank you for your assistance!
$currentLetter = '';
foreach($content as $botanyWord=>$definition) {
if ( $currentLetter !== $botanyWord[0] ) {
$currentLetter = $botanyWord[0];
// next letter ...if your array is in lex. order
...
}
...
}

Categories