php - why showing value of last item from array? - php

Ok, I have this code
<?php //getting values
$column1 = $params->get('param1','');
$column2 = $params->get('param2','');
$column3 = $params->get('param3','');
$column4 = $params->get('param4','');
$column5 = $params->get('param5','');
//setting array and filter the empty values
$getvalues = array($column1,$column2,$column3,$column4,$column5);
$values = array_filter($getvalues); ?>
then I am using these values inside a foreach
<?php foreach ( $values as $key=>$value ) : ?>
<div><?php echo $value; ?></div>
<?php endforeach; ?>
It does the job, but after the loop, it adds the last item's value. Why?

After a foeach loop the used $key and $value variables are still alive and holds their last values so i think you are using the $value somewhere else in you code whithout rewriting it's value.
Call unset($value) and unset($key) after the loop and watch the PHP errors i think you will face some if the error reportnig is set to the most strict mode.

Related

undefined index invalid argument for loop error

Please point me in the right direction here Im trying to do the following:
Multiple select boxes are generated for each eventid
User choose who they think will win each event
The name of each selectBox is the event id assigned to variable $id
At end of while loop I want to extract the array $id value in For loop, however im getting error "undefined offset & invalid argument" on my for loop...
Here is my form
$i=0;//counter
while($row=mysql_fetch_array($result)){
$team1 = $row['team1'];
$team2 = $row['team2'];
$id[$i]= $row['event_id'];
echo'<h3>'.$team1.' VS '.$team2.'</h3>';
echo'<select name="'.$id[$i].'">';
echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
echo'</select>';
$i++;
}//while
Here is my for loop giving error, I suspect problem is in the
$_POST['$id']...
if(isset($_POST['submit'])){
foreach($_POST[$id] as $eventId => $winner){
echo'<h3>'.$eventId.'</h3>';
}//for loop
}//end isset
Any help will be greatly appreciated
$id is defined as an array here$id[$i]= $row['event_id'];. Arrays can not be used as a key in a foreach array or otherwise.
This is what is causing you an error on this line
foreach($_POST[$id] as $eventId => $winner){ //$id is an array of values
echo'<h3>'.$eventId.'</h3>';
}//for loop
You have to make a second foreach statement for the $id then use the id values in your current foreach statement.
foreach( $id as $key => $val ) {
foreach( $_POST[$val] as $eventId => $winner){
You don't know what the event_id values are on the action page, so I think you'll have to query for those again something like:
if(isset($_POST['submit'])){
/* do your query here */
$data = array();
while($row=mysql_fetch_array($result)){
$data[] = $_POST[$row['event_id']];
}
foreach($data as $key => $value){
print_r($_POST[$value]);
echo "<br>";
}
}

Grabbing key value from a mysql query

I thought this was quite basic but for some reason I can't figure it out.
I have this query
$result = mysql_query("SELECT * FROM Users.Information LIMIT 0,1");
To grab the data (such as firstName, lastName), I use this snippet of code
<?php while ($row = mysql_fetch_assoc($result)): ?>
<?php foreach($row as $key=>$value) {
echo $value;
} ?>
<?php endwhile; ?>
which correctly prints everything I want.
Now in a separate table, I want to have it such that I will print the individual values separately. I thought this was quite simple like
first name:
however, this does not work. If I just do $value, of course this makes sense, but it prints the last value in the array.
How do I grab individual values? Do I just parse $value into different values, or is there an easier way?
Thank You.
$data = array() ; //Create a storage, so you can access it later.
<?php while ($row = mysql_fetch_assoc($result)): ?>
$data[] = $row ; //Add the value to storage.
<?php foreach($row as $key=>$value) {
echo $value;
} ?>
<?php endwhile; ?>
We are ready. We have $data array with all rows. Now you can manipulate it, access elements, pass somewhere.
$data[0] ; //Access the first element
echo $data[0]['FirstName'] ; //Print first name of the first row.

Having difficulties with php foreach and passing by reference

I'm pulling some data from a database (with a function I have called query), and I want to add another key/value pair to each result, i.e.:
$items = query("SELECT * FROM items");
foreach($items as &$item) {
$item['fixedname'] = str_replace(' ','_',$item['name']);
}
Now I want to put these on an html view, i.e.:
<?php foreach($items as $item): ?>
<div id="<?= $item['fixedname'] ?>" ><?= $item['name'] ?></div>
<?php endforeach; ?>
However, this doesn't output correctly. For instance, when the query returns two items, the loop in the php outputs the same thing twice. If there are three: it outputs the first one, then two of the second one. What's the problem here?
When modifying using foreach() I've had weird results on occasion. I use
foreach ($items as $key=>$value) {
$items[$key] = modified($value);
}
Or, why not do it in the SQL SELECT your, fields, here, REPLACE(name, ' ', '-') AS fixedname
The data returned on the right side of the foreach is a copy of the data, it can't be modified directly. Instead you need to fetch both the $key (the ID of the item in the array) and the $item. By letting PHP telling you the $key you don't need to worry about whether the array is normal (e.g. having indexes of 0,1,2,...) and associative.
This example would walk the $items array and add 'fixedname' into it.
foreach($items as $key => $item) {
$items[$key]['fixedname'] = str_replace(' ','_',$item['name']);
}
You could do a normal for loop
<?php
for($i=0; $i < count($items); $i++){
$items[$i]['fixedname'] = str_replace(' ','_',$items[$i]['name']);
}
?>
Then everything will be ready when you go to your next foreach.
u have bunch of wrong things
1- dont use mysql , use PDO or mysqli instead
2- $items = query("SELECT * .... --->Call to undefined function query()
change it to
$items = mysql_query("SELECT * ....
3- Invalid argument supplied for foreach() ,
you missed to fetch your query
try this whole code
$items = mysql_query("SELECT * FROM items");
?>
<?php while ($row = mysql_fetch_array($items) ) {?>
<div id="<?php echo $row['fixedname'] ;?>" ><?php echo $row['name']; ?></div>
<?php } ?>

How to set condition for same attribute values in foreach loop - php - xml

i am getting data from xml feed and then using foreach loop inserting data in mysql.
but xml feed contains multiple items with same attribute like this
but what i want is ,
the addition of subitems of the attributes having same values
as xml shows the attribute tag1111 has 3 types of values
if i add something in foreach loop it gets replaced for every loop.
how can i do this ?
<?php
$requestUrl = "url";
$data = simplexml_load_file($requestUrl);
$i=0;
foreach($data->item as $subitem) {
if(!in_array($data->item[$i]['promocode'], $arr_promocode))
$arr_promocode[] = $data->item[$i]['promocode'];
else{
$key = array_search($data->item[$i]['promocode'], $arr_promocode);
$data->item[$key]['clicks'] = $data->item[$key]['clicks'] + $subitem->clicks;
}
$arr_program[] = $data->item[$i]['program'];
$arr_program_name[] = $data->item[$i]['program_name'];
$clicks = $subitem->clicks;
$total = $subitem->total;
$i++;
}

How do I code a loop for my echo statement?

I get only one printed result in the foreach echo loop at the bottom of the page.
<?php
defined('_JEXEC') or die('Restricted access');
$db =& JFactory::getDBO();
$query0 = "SELECT * FROM `jos_ginfo` WHERE . . . LIMIT 30";
//echo $query0;
$db->setQuery($query0);
$ginfo = $db->loadObjectList();
//echo
//$ginfo[0];
foreach($ginfo as $ginfo[$i]):
{$i=0; $i++;}
endforeach;
echo $db->getErrorMsg();
if(empty($ginfo)){
echo "<center>No
game found, try a different entry.</center>";
}else{
$pgndata = array ( $ginfo[$i]->Id);
$i=0;
foreach($pgndata as $ginfo[$i]->Id):
//I am only getting one printed result!
{
echo "<a href='/index.php?option=com_publishpgn&tactical-game=".$ginfo[$i]->Id."&Itemid=78.html'>\n";
echo "".$ginfo[$i]->White." v. ".$ginfo[$i]->Black." (".$ginfo[$i]->Result.") ".$ginfo[$i]->EventDate." ECO:".$ginfo[$i]->ECO."</a><br>\n";
$i++;
}
endforeach;
//echo "</div>";
}
?>
A few errors in your code:
foreach($ginfo as $ginfo[$i]):
{$i=0; $i++;}
On the first iteration, $i is undefined, so the first value pulled from $ginfo for the foreach loop will be stored in $ginfo[null]. You then set $i to 0, increment it, and loop around, so now the next value gets stored in $ginfo[1], as will all further iterations. So you end up with only two values extracted from the $ginfo object, and stored in the 'null' and '1' keys.
Later, you do
$pgndata = array ( $ginfo[$i]->Id);
You're not doing this inside a loop, so $pgndata becomes an array with a single element taken from $ginfo[1]->Id. You then immediately do
foreach($pgndata as $ginfo[$i]->Id):
but $pgndata has only a single element in it, which explains why you only have one item output.
I don't know what your ->loadObjectList() at the top does. Is it returning an array? An object? If it's any array, what's the point of the first foreach loop? You're destroying all but the first two values present in it.
It's never ever a good idea to try and modify an array WHILE you're looping over it in a foreach loop. It's kinda like trying to change a tire and axle and transmission on your car while going down the highway at 100mph. You might get lucky once, the rest of the time you're going to be spread into a thin ketchup stain.
Also, why are you mixing the {} and : / end syntaxes? Choose one or the other, but don't use both. Braces are standard and universally understood. the :/end version is far less popular and unfamiliar to most people.
I suppose, you need this:
$ginfo = $db->loadObjectList();
foreach($ginfo as $value)
{
echo $value . '<br />';
}
Further, see foreach manual and other loops.
$query = mysql_query("select * from table");
while ($result = mysql_fetch_array($query))
{
echo "$result[id]";
echo "$result[firstname]";
}
This is a modified version of Sarfraz's code.
Try this..
// Array of multiple games
$ginfo = $db->loadObjectList();
// Loop through games array
foreach ($ginfo as $index => $singleGameInfo)
{
foreach($singleGameInfo as $elementName => $elementValue)
{
echo "[$elementName \"$elementValue\"]\n";
}
}
In place of...
echo "[Event \"".$ginfo[0]->Event."\"]\n";
echo "[Site \"".$ginfo[0]->Site."\"]\n";
echo "[Date \"".$ginfo[0]->Date."\"]\n";
echo "[Round \"".$ginfo[0]->Round."\"]\n";
echo "[White \"".$ginfo[0]->White."\"]\n";
echo "[Black \"".$ginfo[0]->Black."\"]\n";
echo "[Result \"".$ginfo[0]->Result."\"]\n";
echo "[ECO \"".$ginfo[0]->ECO."\"]\n";
echo "[WhiteElo \"".$ginfo[0]->WhiteElo."\"]\n";
echo "[BlackElo \"".$ginfo[0]->BlackElo."\"]\n";
echo "[Annotator \"".$ginfo[0]->Annotator."\"]\n";
echo "[SetUp \"".$ginfo[0]->SetUp."\"]\n";
Edit: Are you trying to loop through multiple games or the field-data of a single game?
Edit2: Updated to loop through games

Categories