Trouble displaying results correctly from FOREACH loop - php

I switched my code to PDO and I almost there, except for this part where all results from a query are supposed to be displayed with a foreach statement. I know the data is being fetched properly and is correctly stored in $row2.
What I need to do is get take the 'position' variable from $results2 and add 1 to it and then run the foreach loops where position is equal to that new number...
BEFORE I SWITCHED TO PDO, my code was working perfectly and this did correctly display the 2 expected results:
$cont = $results2[0]->position;;
$cont++;
foreach ($results2 as $resulting) {
if ( $results2[0]->position = $cont )
{
echo "<hr><br><br>" . $resulting->text . " " . " <b>Suggested by: $resulting-
>display_name </b><br>|<b> Approve this contribution</b> | <b>delete this suggestion</b> |";
}
}
But now, the foreach only returns the same first result twice after the conversion to PDO, which looks like this:
//NEW PDO CODE--DOESN'T DISPLAY BOTH RESULTS:
$results2->execute();
$row2 = $results2->fetchAll(PDO::FETCH_ASSOC);
$cont = $row2[0]['position'];
$cont++;
foreach ($row2 as $resulting) {
if ( $row2[0]['position'] == $cont )
{
echo "<hr><br><br>" . $row2[0][text] . " " . " <b>Suggested by:" . $row2[0]
[display_name] . "</b><br>|<b> Approve this contribution</b> | <b>
delete this suggestion</b> |";
}
}

It looks like your old code was fetching an array of objects, whereas your new code is fetching an array of arrays (indicated by PDO::FETCH_ASSOC).
So while $results2[0]->position used to work, you mistakenly replaced it with $row2[0][position]. However, position needs to be quoted in the second case since it is an array index.
If you had all of your error reporting turned on, you would have easily seen this.
The same applies to $row2[0][text] and $row2[0][display_name]. In addition to the lack of quotes on these indexes, you probably really want $resulting instead of $row[0] since $row[0] will give you the same values each time through the loop. So those should probably be changed to $resulting['text'] and $resulting['display_name']
So replace all instances of $row2[0][position] with $row2[0]['position']. Also, heed the advice of John Ruddell.

NOTE: this is not an answer... its just a way for me to clarify what I was saying in comments because its hard to show code in comments.
GENERAL IF CODE LOGIC:
if (true){
// code will always execute on true
}
if (false){
// code will never execute on false
}
sample:
$key = "12345";
if($key){
// will always be executed because this is a true statement.
}
your code:
if ( $row2[0]['position'] = $cont ){
// will always execute because the assignment is true
}
NOW:
with all that aside.. if nothing is happening when you run it with == that means that the count is not equal to the $row[0][position] so its a false statement and the code inside the if does not get executed.
RECOMMENDATION:
try putting an echo $cont; and echo $row2[0]['position']; before the if statement to see whats going on.

Related

PHP compare subsequent array element to previous

So i'm having trouble getting a bit of code to work. Essentially what I want to do is:
in a foreach loop, if a given array value is set, compare that existing value to the current loop value, then set the existing value = current value (for the iteration) if the existing value is already greater than current val. Here is the code i'm working with:
if ($usedebayxml->ack == 'Success') {
foreach($usedebayxml->searchResult->item as $key => $value) {
if(isset($newarray[1]['TotalCost'])) {
if($newarray[1]['TotalCost'] > ((integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice)) {
$newarray[1]['Title'] = (string)$value->title ;
$newarray[1]['ShippingCost'] = (integer)$value->shippingInfo->shippingServiceCost;
$newarray[1]['Price'] = (integer)$value->sellingStatus->currentPrice;
$newarray[1]['Condition'] = 'New';
$newarray[1]['TotalCost'] = (integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice;
}
}
else
$newarray[1]['Title'] = (string)$value->title;
$newarray[1]['ShippingCost'] = (integer)$value->shippingInfo->shippingServiceCost;
$newarray[1]['Price'] = (integer)$value->sellingStatus->currentPrice;
$newarray[1]['Condition'] = 'Used';
$newarray[1]['TotalCost'] = (integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice;
}
}
With this code, what is returned is ultimately the values in the LAST key object in the xml file (im using simpleXML if that helps). In other words, i don't think the first if block (if isset) is being entered into, and the values are being set to whatever the values are for the current iteration. Can anyone see any flaw in my logic here? I've been stumped on this one for a while.
I am a supreme idiot. The logic here is fine, i was just missing a { for the opening else block. dur! After adding this, this bit of code works as intended :)
I'm surprised though that i wasn't throwing any errors without having this....I think that was probably throwing me off in determining why it wasn't working originally.

lost var in php

I am fairly new to PHP and Yii, and the problem that I am not nor as the question in google, so the only thing I can think of is to ask the question to this list that I have solved many problems.
The issue is as follows: in the code that I attached, I read several records that I keep in array and after the process.
Well, if you look at the debug entries in foreach in he first, all goes well and the variable $items is loaded, but when I get to the second debug $items variable has the correct number of elements, but the elements are empty : count ($items) = 2 but $items[0] and $items[1] are null
$idiomas=CListaMidiomas::model()->findAll();
$items=array();
$nombre=array();
$a=0;
foreach ($idiomas as $idioma){
$nombre[$a]=$idioma->sIdioma;
$items[$a]=TblCategoriastexto::model()->findAll(
array('condition'=>'id='.$data->id.' AND idIdioma='.$idioma->id_idioma));
echo "<br>---AAAAAAAAAAA--".$a."-----------<br>";
CVarDumper::dump($items); //in this moment is correct
if (empty($items[$a]) ||$items[$a]==null ){ // not enter because $items have content
$items[$a]=new TblCategoriastexto();
$items[$a]->idIdioma=$idioma->id_idioma;
}
$a++;
}
echo ">>>>>>>>>>>>>>>".count($items) ; //<<<<<<<<<<present 2
CVarDumper::dump($items); // but in this moment t0 2 are null
for ($a=0;$a<count($items) ;$a++){
echo "<b>".CHtml::encode($nombre[$a]).":</b>";
$out="";
$item=$items[$a];
echo "<br>-----".$a."-----------<br>";
CVarDumper::dump($items[$a]);<<<<<<<<<<<<<<<<<<<<<<<<null
for ($b=1;$b<=20;$b++){
$campo="tc".$b;
$out.=$items[$a]->$campo . ",";<<<<<<<<<<<<<<<<error
}
echo CHtml::encode($out);
echo"<br>";
}
This line: if (empty($items[$a]) ||$items[$a]=null ){ will always assign $items[$a] to null.
To compare values, use the comparison (for equality) operator, == instead of the assignment operator =.
Try changing this line:
if(isset($items[$a]->$campo)) {
$out.=$items[$a]->$campo . ",";
}

PHP Array issue when looping and echoing

I'm having trouble getting the array to work right, let me show you the code here
function scanArray(){
$al = sizeof($_userLoaders);
echo $al. "<br />";
for ($tr = 0; $tr <= $al; $tr++) {
echo "value: " .$tr. "<br />";
echo $_userLoaders[$tr];
}
}
//Fetch user's loaders.
$_userLoaders;
function get_user_loaders(){
$con = connectToMySQL();//connects to my_sql
mysql_select_db("my_database", $con);//connect database
$t = mysql_query("SELECT * FROM someTable
WHERE value_a=".$_SESSION['value_a']." AND value_b=someValue");
$x= 0;
//lets loop through the results and create an array to compare later.
while ($result = mysql_fetch_array($t)){
$_userLoaders[$x] = $result['value_c'];
$x++;
}
//lets get all the options for
print_r($_userLoaders);//this part prints what it should
scanArray();
}
okay, I minimized the code above to show you what's going on. Pretty much function get_user_loaders() works great. It fetches data from a table in a database, and returns what it should. Second, it makes an array out of it. Again, this part works great. When the print_r() method is called it prints what it should, here's an example of what it prints:
Array ( [0] => tableValue )
yes, at this point it only has one value, please note that this value can vary from no values to 100 values which is why I am using an array. In this case, i'm testing it with one value.
Now, once I call scanArray() It doesn't echo the values.
the scanArray() function echoes the following:
0
value:
so what I don't understand is why does it print it out, but it doesn't display the function? Thanks in advance.
Your problem is that $_userLoaders variable is declared outside the function and function scanArray knows nothing about it. You need to either pass that variable in as a parameter:
function scanArray($_userLoaders) {
...
}
with the call at the end being
scanArray($_userLoaders);
or alternatively declare the variable as global inside the function:
function scanArray($_userLoaders) {
global $_userLoaders;
...
}
That would be because $_userLoaders is not equal to anything inside your scanArray() function. While it's not good practice, you can add the line:
global $_userLoaders;
to your scanArray() function and every other function that uses that global variable then, and it should work.

Changes to a PHP Array Not "Sticking"

OK so I'm making something to do some data mining but I do changes to an array (by overwritting previous array values) in a loop and they show that they've been changed but once I get outside of a greater loop the values change back to their original values.
Probably easier to give an example:
It starts off like this, turning a bunch of the parts of the array into the word "MATCH".
Now if I was to immediately dump the values of the array it would show that some values have changed to "MATCH" (ie, right after changing the value I would echo the array slot and it would show it's value to be "MATCH") However after I get outside the loop the array changes back to it's original contents
Here is a compressed version of the code:
//i've got this big loop for doing the main work
do {
//Set dat ticker
$q = 0;
// Run through entire previous scrape array to check for matches and mark them as unchanged
do {
if ($itemTitle[$i] == $prodURLS[$q]) {
$prodURLS[$q] = "MATCH";
echo "When the value is printing immediately it shows that it's changed: ".$prodURLS[$q]."<br>";
}
$q++;
} while ($q < $urlArraySize);
$i++;
} while ($i < $itemtitleArraySize);
//If I were to try to print the variable down here it would be reverted to like it was before I changed it to "MATCH"
print_r($prodURLS);
From running your code, setting the variables as follow, it works for me:
$prodURLS = array('a','b','c');
$itemTitle = array('a');
$urlArraySize = count($prodURLS);
$itemtitleArraySize = count($itemTitle);
$i = 0;
My only recommendations with only this amount of information, are:
To provide more context information, as madth3 suggests.
To check the scope in which you are setting/checking values. You may need the & operator to pass variables by reference, or the global keyword to use global variables.
To use the foreach loop, it will make your code smaller and easier to read. Also you won't need to count the size of the arrays and will have other advantages, e.g. in the use of associative arrays. Again, be careful about the use of variables by reference. For example:
foreach ($itemTitle as $item) {
foreach ($prodURLS as &$prod) {
if ($item == $prod) {
$prod = 'MATCH';
}
}
}
unset($prod); //Unset variable set by reference if you are going to use it later on!
Also, you may find useful some of the php array functions like array_walk. Check out the PHP Manual on the array functions reference.
Really, there isn't a lot that can be said from just the code you provided.
Good luck.

How do I use multiple list()/each() calls in a while loop?

I'm working with 3 different arrays (although I'm only testing with two for the time being) and I'm trying to process the arrays on $_POST. I'm currently using:
while(list($key_member,$member)=each($_POST['member_ids'])
&& list($key_amount,$amount)=each($_POST['payment_amounts']))
{
echo "MEMBER: $member<br>";
echo "AMOUNT: $amount<br><br>";
}
If I use one list() on either array it will print the info for that particular item. However, if I attempt to use multiple list() commands in the while, only the last list()ed item gets filled properly. Is list() doing some trickery in the background that's preventing it from working in a while loop?
Obviously the "easy" solution would be to use an index and simply force the issue, but I prefer enumerating -- and I'm honestly just curious as to
What am I doing wrong, and/or what is "broken" with list()?
bug? dunno.
here's a workaround.
while(list($key_member,$member)=each($_POST['member_ids'])){
list($key_amount,$amount)=each($_POST['payment_amounts']);
echo "MEMBER: $member<br>";
echo "AMOUNT: $amount<br><br>";
}
You could extract each array's keys using array_keys(), which produces an indexed array, then keep separate loop counters for each array:
$member_ids = array_keys($_POST['member_ids']);
$amounts = array_keys($_POST['payment_amounts']);
$mi = 0;
$am = 0;
while(1) {
...
$mi++
$am++;
if (count($member_ids) >= $mi) && (count(amounts) >= $am) {
break;
}
}
&& is evaluated in a short-circuit manner, the first statement to return false jumps out of it. In your case it stops to iterate as soon as the first array is at its end. list should work fine here, as it's a language construct which assigns variables.

Categories