PHP Foreach loop not working with variable - php

I'm sorry, if this is duplicate post, but somehow i can't get my loop working with variable. if i echo this inside foreach i get my data but if i use variable i get data for only the first item from my array.
my code `
$user - My arrray
$count = $user['count'];
$echo = "";
foreach($user as $val => $key)
{
if($val == 'true')
{
for($x = 0; $x < $count; $x++)
{
$name = $user[$val][$x]['name'];
$id = $user[$val][$x]['id'];
$staatus = $user[$val][$x]['status'];
$feed = $user[$val][$x]['feed'];
/* Now when am using only echo, instead of $echo it will work flawlessly,
but i want to echo it using an variable called $echo.
I call the variable on my html page where the forms are,
but i'm only getting data for the first element.
Short, i want to display my data under the form.*/
$echo = "
<table class='table'>
<tr>
<th>NIMI</th>
<th>ID</th>
<th>STAATUS</th>
<th>FEED</th>
</tr>
<tr>
<td>$name</td>
<td>$id</td>
<td>$staatus</td>
<td>$feed</td>
</tr>
</table>
";
}
}
}
<?php echo $echo; ?> for calling.
I'm quite a beginner in this thing so maybe someone could help. I also searched around, tried different things but it's not working. I also tried to display data without for loop, but it's not working either.
Also if there's any improvments i could do with my code please tell me. Like make it shorter etc, i'm here to improve so why not :D

You're missing the . in your $echo .= "
$echo .= "
<table class='table'>
<tr>
<th>NIMI</th>
<th>ID</th>
<th>STAATUS</th>
<th>FEED</th>
</tr>
<tr>
<td>$name</td>
<td>$id</td>
<td>$staatus</td>
<td>$feed</td>
</tr>
</table>
";

Related

Display data from database inside <table> using wordpress $wpdb insdie a shortcode

The code below prints into one block without formatting. Given that shortcodes already run php am I specifying the html properly? It doesnt feel like it since the HTML portion doesnt seem to be working for me. It jsut outputs as an entire block. (see picture)
function trying_2() {
'
<table border="1">
<tr>
<th>name</th>
<th>partysize</th>
<th>phonenumber</th>
</tr>';
global $wpdb;
// sending query
$result = $wpdb->get_results ("SELECT * FROM table_name");
foreach ( $result as $print ) {
echo '<tr>';
echo '<td>' . $print->name.'</td>';
echo '<td>' . $print->partysize.'</td>';
echo '<td>' . $print->phonenumber.'</td>';
echo '<td>' . $print->emailaddress.'</td>';
echo '<td>' . $print->Time_stamp.'</td>';
echo '<td>' . $print->currentstatus.'</td>';
'</tr>';
}
'</table>';
}
add_shortcode('tryin', 'trying_2');
You are not formatting the HTML / table correctly hence why you are getting everything printed in one line on your page in wordpress.
You do not need to echo each td separately. You just to wrap have one variable define for to be echoed and in your function and just use and you just need to concatenate the loop data to that variable.
Just paste this below code in your active theme functions.php file and then call your short code [tryin] in a page. (Code tested and works)
function trying_2() {
global $wpdb;
$results = '<table border="1">
<thead>
<tr>
<th>name</th>
<th>partysize</th>
<th>phonenumber</th>
<th>emailaddress</th>
<th>Time_stamp</th>
<th>currentstatus</th>
</tr>
</thead>
<tbody>';
// sending query
$WPQuery = $wpdb->get_results ("SELECT * FROM table_name");
foreach ( $WPQuery as $print ) {
$results .= "<tr>
<td>$print->name</td>
<td>$print->partysize</td>
<td>$print->phonenumber</td>
<td>$print->emailaddress</td>
<td>$print->Time_stamp</td>
<td>$print->currentstatus</td>
</tr>";
}
$results .= "</tbody>
</table>";
//Print results
echo $results;
}
add_shortcode('tryin', 'trying_2');

Using Foreach to print the values

Stored JSON decoded data in a variable that variable array of data I need to print that I tried below code but I get a result in that one bug called see below image.
You could try writing
$pack = json_encode($packs,true);
out of echo, just below
$packs=data['packs'];
$no = 1;
while($data = mysqli_fetch_array($findCustomer,MYSQLI_ASSOC)){
echo '
<tr>
<td>'.$no.'</td>
<td>'.$data['NAME'].'</td>
<td>'.$data['PHONE'].'</td>
<td>'.$data['STB_NUMBER'].'</td>
<td>'.$data['VC_NUMBER'].'</td>
<td>'.$data['agent_name'].'</td>
<td>'.$data['created_on'].'</td>';
echo '<td>';
$array =$data['packs'];
$pack = json_decode($array,true);
foreach ($pack as $value) {
echo 'Pack-Name:'.$value['pack_dsc']."<br>Pack-Amount:".$value['pack_base_prc']."<br>";
}
echo '</td>
</tr>';
$no++;
}

Variable Defined in Else Is Ignored in If

I'm trying to build divs based on unique values. So for each line, the script checks the team name against $tempTeam. If they're equal, the line gets added to the table in the existing div. If they're not equal, a new div and table is created, and the line is added there.
However, the if part isn't recognizing when $tempTeam is equal to the team so it never runs, even though the else part is properly setting $tempTeam. So I'm wondering why the variable is working for the else part of the code, but not the if part.
Here's the full code, although the trouble begins when I first define $tempTeam. Thanks for any help.
<?php
$csv = file_get_contents('schedules.csv');
$csv_array = explode("\n", $csv);
unset($csv_array[count($csv_array) - 1]);
$headers = explode(",", $csv_array[0]);
// iterate through all lines of CSV, skipping first header line
for($i=1;$i<count($csv_array);$i++) {
$line = explode(",", $csv_array[$i]);
// iterate through all headers and assign corresponding line value
foreach ($headers as $index => $header){
$parsed_array[$i][$header] = $line[$index];
}
}
// create divs and tables
$tempTeam = '';
foreach ($parsed_array as $i => $match) {
if ($tempTeam == $match['Team']) {
echo "
<tr><td>$match[Date]</td><td>$match[Result]</td><td>$match[Location]</td><td>$match[Opponent]</td></tr>
";
}
else if ($tempTeam == '') {
$tempTeam = $match['Team'];
echo "
<div class=\"schedule\" data-container=\"$match[League]\">
<table>
<thead>
<tr>
<th colspan=\"4\">$match[Team]</th>
</tr>
<tr>
<th>Date</th><th>Result</th><th>Location</th><th>Opponent</th>
</tr>
</thead>
<tbody>
<tr><td>$match[Date]</td><td>$match[Result]</td><td>$match[Location]</td><td>$match[Opponent]</td></tr>
";
}
else {
$tempTeam = $match['Team'];
echo "
</tbody>
</table>
</div>
<div class=\"schedule\" data-container=\"$match[League]\">
<table>
<thead>
<tr>
<th colspan=\"4\">$match[Team]</th>
</tr>
<tr>
<th>Date</th><th>Result</th><th>Location</th><th>Opponent</th>
</tr>
</thead>
<tbody>
<tr><td>$match[Date]</td><td>$match[Result]</td><td>$match[Location]</td><td>$match[Opponent]</td></tr>
";
}
}
echo "
</tbody>
</table>
</div>
";
?>
For a start, look at the first line of the else clause:
$tempTeam == $match['Team'];
I'm pretty certain that's not what you wanted to do, it seems to me that assignment would probably be a better choice than comparison.
What you're doing is no different to:
$a = 1;
$a == $a + 1;
print ($a);
which will still output 1 rather than 2. If you want do do assignment, it should have just the one = character:
$tempTeam = $match['Team'];

xml to php table alternating row color

Trying to display an html table from and xml from php, getting error when trying to alternate the row base on even and odd mostly for styling the table.
foreach($bookdata as $book) // loop through our books
{
$i = 0;
if($i%2 == 0)
{
$class = 'even';
}
else
{
$class = 'odd';
}
{
echo <<<EOF
<tbody>
<tr class='$class'>
<td>{$book->date} </td>
<td><a href='http://www.website.com{$book->dataNo}.html'>{$book->Name}</td>
<td><a href='http://www.website.com/-{$book->authorcodeNo}.html'>{$book->author}</td>
</tr>
}
$i++;
}
EOF;
}
echo '</tbody>';
echo '</table>';
Any help most welcome
$i = 0;
foreach($bookdata as $book) // loop through our books
{
...
...
//and at end of foreach
$i++;
You are redeclaring $i inside of your for loop so it's never going to actually increase, just get reset to 0 every single time. Also, not sure what's up with some of your curly braces as there's not enough code to see it all as far as I can tell... start by moving your variable declaration outside the for loop though!
You are reseting the $i to 0 on every loop.
Remove
$i = 0;
from your code. And I didn't notice this before but the EOF is misplaced. Here is a full working solution
foreach($bookdata as $book) // loop through our books
{
if($i%2 == 0) { $class = 'even'; }
else { $class = 'odd'; }
echo <<<EOF
<tbody>
<tr class='$class'>
<td>{$book->date} </td>
<td><a href='http://www.website.com{$book->dataNo}.html'>{$book->Name}</td>
<td><a href='http://www.website.com/-{$book->authorcodeNo}.html'>{$book->author}</td>
</tr>
EOF;
$i++;
}
try put the $i=0 out of foreach loop.

Problem with loop printing csv contents in php

This snippet just about works :|
I can spit out all of the array data, but what I want is to be able to print out the data column by column.
function processCSV()
{
global $uploadFile;
$loadLocationCsvUrl = fopen($uploadFile,"r");
if ($loadLocationCsvUrl <> false)
{
while ($locationFile = fgetcsv($loadLocationCsvUrl, ','))
{
$csvCols = array(
'country' => $locationFile[9],
'open' => $locationFile[4],
'officeid' => $locationFile[2]
);
foreach($csvCols as $locationData)
{
if ($locationData == '') {
echo "<p>" . "blank" . "</p>";
}
else
{
echo "<p>" . $locationData . "</p>";
}
}
}
}
fclose($loadLocationCsvUrl);
}
processCSV();
I thought this would work:
echo "<p>" . $locationData['country'] . "</p>";
But if I do that I see a incorrectly formatted page, like the below (uploaded screenshot).
http://www.imageupload.org/?d=9C676F041
I managed to work this out with a different implementation, I switched to a 2d array, the table rendering was never the issue it was obtaining the data.
<?php
function processCSV()
{
global $uploadFile;
$loadLocationCsvUrl = fopen($uploadFile,"r");
if ($loadLocationCsvUrl <> false)
{
while ($locationFile = fgetcsv($loadLocationCsvUrl, ','))
{
$officeId = $locationFile[2];
$country = $locationFile[9];
$open = $locationFile[4];
echo "<table>";
echo "<tr>";
echo "<td>$officeId</td>";
echo "<td>$country</td>";
echo "<td>$open</td>";
echo "</tr>";
echo "</table>";
}
}
fclose($loadLocationCsvUrl);
}
processCSV();
?>
Thank you for responding and sorry if I wasted anybodies time.
It sounds like you want to display the output colum-wise. In that case a <table> is the intended markup. But I would first simplify your code:
// read in
$csv = array_map("str_getcsv", file($uploadFile));
// output
print "<table>";
foreach ($csv as $row) {
print <<<HTML
<tr>
<td>$row[9]</td>
<td>$row[4]</td>
<td>$row[2]</td>
</tr>
HTML;
}
If you don't use the associative array keys for the columns, then there's no point in creating them.
<p> is a block element, so each successive one goes to a new line by design. You can set 'display: inline;' in your css if you want, but then why use <p>?
You could use an inline element like <span> or use 'float: left' to make a block element behave as you want.
That's assuming the data isn't appropriate for tabulation.
make a parent table then tr and td,
now, inside this td, make a table and print a column of td-trs
then close this table
print a new td in parent
repeat a table of one column trs
example....
<table><tr><td>
<table>
<tr><td>col1stuff1</td></tr>
<tr><td>col1stuff2</td><tr>
<tr><td>col1stuff3</td><tr>
</table>
</td><td>
<table>
<tr><td>col2stuff1</td></tr>
<tr><td>col2stuff2</td><tr>
<tr><td>col2stuff3</td><tr>
</table>
</td><td>
<table>
<tr><td>col3stuff1</td></tr>
<tr><td>col3stuff2</td><tr>
<tr><td>col3stuff3</td><tr>
</table>
</td></tr></table>

Categories