change for loop in foreach - php

I'm new to php.I'm reading a RSS feed and store in my database table.
for this I'm using
$num = count($movies->channel->item);
for ($i=0; $i<=$num-1; $i++){
$tittle= $movies->channel->item[$i]->title."<br/>";
$link=$movies->channel->item[$i]->link."<br/>";
$image=$movies->channel->item[$i]->medium_image_url."<br/>";
$des=$movies->channel->item[$i]->description."<br/>";
$city=$movies->channel->item[$i]->city;
}
how can display all data with foreach loop?

foreach($movies->channel->item as $opt){
echo $tittle= $opt->title."<br/>";
echo $link=$opt->link."<br/>";
echo $image=$opt->medium_image_url."<br/>";
echo $des=$opt->description."<br/>";
echo $city=$opt->city;
}

You can just echo out the result of your statements (I've also changed it to a foreach as requested):
foreach ($movies->channel->item as $item) {
$tittle= $item->title."<br/>";
$link=$item->link."<br/>";
$image=$item->medium_image_url."<br/>";
$des=$item->description."<br/>";
$city=$item->city;
echo $tittle.$link.$image.$des.$city;
}

This should work:
foreach ($movies as $movie)
$tittle = $movie->title."<br/>";
$link = $movies->link."<br/>";
$image = $movie->medium_image_url."<br/>";
$des = $movie->description."<br/>";
$city = $movie->city;
}

foreach ($movies->channel->item as $item) {
echo $item->title.'<br />';
echo $item->link.'<br />';
echo $item->medium_image_url.'<br />';
echo $item->description.'<br />';
echo $item->city;
}
I have echoed them because I think this is what you are wanting to do - your code reassigns variables on each iteration but does nothing with them. They are overwritten each time, so they will only hold the values from the last iteration at the end.
EDIT
You can easily modify this to insert rows into your database by doing something like this:
foreach ($movies->channel->item as $item) {
echo $item->title.'<br />';
echo $item->link.'<br />';
echo $item->medium_image_url.'<br />';
echo $item->description.'<br />';
echo $item->city.'<br />';
// Build the query - change the names of your table and columns as appropriate
$query = "INSERT INTO `tablename`
(`title`,`link`,`medium_image_url`,`description`,`city`)
VALUES
('$item->title','$item->link','$item->medium_image_url','$item->description','$item->city')";
// Do the query - do NOT show the output of mysql_error() in a production environment!
if (!mysql_query($query)) echo 'Oh no! Something went wrong with the query: '.mysql_error();
}
Alternatively, you can turn it all into one query, to minimise database traffic:
$rows = array();
foreach ($movies->channel->item as $item) {
echo $item->title.'<br />';
echo $item->link.'<br />';
echo $item->medium_image_url.'<br />';
echo $item->description.'<br />';
echo $item->city.'<br />';
// Add this entry to $rows
$rows[] = "('$item->title','$item->link','$item->medium_image_url','$item->description','$item->city')";
}
// Build the query - change the names of your table and columns as appropriate
$query = "INSERT INTO `tablename`
(`title`,`link`,`medium_image_url`,`description`,`city`)
VALUES ".implode(', ',$rows);
// Do the query - do NOT show the output of mysql_error() in a production environment!
if (!mysql_query($query)) echo 'Oh no! Something went wrong with the query: '.mysql_error();

Related

I am unsure what kind of loop to use in php

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>';

why do I get only 3 return values by using a json link:

there should be many more return values?
print_r($data);
shows that there is much more to be displayed.
Thanks for any hints,
Stefan
<?php
$data = json_decode(file_get_contents('https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-DOGE&type=sell'),TRUE);
//print_r($data);
$ncount = COUNT( $data );
for($i=0;$i<$ncount;$i++){
echo $data['result'][$i]['Quantity'] .'<br />';
}
?>
$ncount should be the count() of $data['result'];
Try this:
<?php
$data = json_decode(file_get_contents('https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-DOGE&type=sell'),TRUE);
$ncount = count($data['result']);
for($i=0;$i<$ncount;$i++){
echo $data['result'][$i]['Quantity'] .'<br />';
}
?>
While not a definite answer, you're running count on $data, but then displaying $data['result']. So if the root array only contains 3 values, you'll only go through the loop 3 times. Instead, try a foreach:
foreach ($data['result'] as $result){
echo $result['Quantity'] .'<br />';
}
You are making things WAY too difficult .. Set result to data['result'] and iterate through that
<?php
$data = json_decode(file_get_contents('https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-DOGE&type=sell'),TRUE);
$result = $data['result'];
foreach($result as $item){
echo $item['Quantity'] . '<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.

Title only if foreach exists

I have the following code:
foreach ($model->details as $detail) {
if ($detail->Title) echo $detail->Title;
if ($detail->Info) echo '<br />'.$detail->Info;
}
Now I want to add something like this:
'<h2>Details</h2>'.'<hr />'
to the top of the output but only when the if's in the foreach clause are met. If neither of the if's is met I want nothing to display at all.
Can some help me tweak my code to accomplish this?
Like so?
foreach ($model->details as $detail) {
if ($detail->Title && $detail->Info) {
echo '<h2>Details</h2><hr />';
}
if ($detail->Title) echo $detail->Title;
if ($detail->Info) echo '<br />'.$detail->Info;
}
Addendum: I'd probably rather do something like this, to also avoid the uneccessary <br /> when there's no Title, but only Info
foreach ($model->details as $detail) {
$text = array();
if ($detail->Title) $text[] = $detail->Title;
if ($detail->Info) $text[] = $detail->Info;
if (!empty($text)) {
echo '<h2>Details</h2><hr />';
echo implode('<br />', $text);
}
}
You need to output to a string, or use the output buffering. The following example uses the string approach:
$sOutputHtml = NULL;
foreach ($model->details as $detail) {
if ($detail->Title) $sOutputHtml .= $detail->Title;
if ($detail->Info) $sOutputHtml .= '<br />'.$detail->Info;
}
if ($sOutputHtml !== NULL) {
echo '<h2>Details</h2>'.'<hr />' . $sOutputHtml;
}

While loop together with foreach

I'm really stuck trying to resolve what should be quite simple.
I Have this
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$id = array('33540116', '33541502');
foreach($id as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
So the code is decoding a json string then using foreach to echo each result.
This json file is rather large and I'm only interested in certain records that match the id's stored in a mysql table.
To do this I have replaced the id array string above with mysql select statement.
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$result = mysql_query("SELECT id FROM people");
$row = mysql_fetch_array($result);
$id = array($row['id']);
foreach($id as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
Although this works, it only gives me 1 result.
What I really need is to loop through the results.
Unfortunately I don't know how to construct a while loop together with foreach.
I will greatly appreciate your assistance.
UPDATE (extra question)
Thanks everyone. You have helped me solve the problem.
However, I have another question that relates to this matter.
I mentioned above that I merely wanted to echo the results.
But this isn't exactly true.
What I really want to do is update the same mysql table with the results retreived from the json file.
I have a table called people with fields id, name and age.
How can I update this table with these results?
Thanks again.
mysql_fetch_array only fetches one row at a time. You can use a while loop to continue fetching rows. The mysql_fetch_array function returns false once the whole result set has been fetched, so that will cause the while loop to terminate as desired.
Also, I removed the foreach loop on $ids. Since there will only be one element in the array it's unnecessary to put the code in a loop.
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$result = mysql_query("SELECT id FROM people");
while ( ( $row = mysql_fetch_array($result) ) ) {
$id = $row['id'];
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
Try this:
while($row = mysql_fetch_array($result)) {
$id = array($row['id']);
foreach($id as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
}
You are using this :
$row = mysql_fetch_array($result);
This will only fetch one row from the database.
If you want to fetch more than one row, you have to call mysql_fetch_array() in a loop :
while ($row = mysql_fetch_array($result)) {
// Work with the current row
}
In your case, you'd have something like this :
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
You do not need foreach loop the while is just enough
$result = mysql_query("SELECT id FROM people");
$id = array($row['id']);
while($row = mysql_fetch_array($result))
{
echo $json->$row['id']->person->{'name'}. '<br />';
echo $json->$row['id']->person->{'age'}. '<br />';
}
You have a couple of issues. Firstly, you shouldn't be using foreach($id as $id) since you are using the same variable for both. Instead it should be foreach($ids as $id). Secondly, you can get a list of the ids and echo out the correct json values as follows
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$result = mysql_query("SELECT id FROM people");
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row['id'];
}
foreach($ids as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
Hopefully that will solve it

Categories