Looping : PhP Array Loops through Database query to output result - php

I have an array called $helloArray which looks like
[peach] => 1
[banana] => 1
[apple] => 1
[pineapple] => 1
[grapefruit] => 2
[tomatoe] => 2
[giger] => 1
[watermelon] => 1
Database columns look like
City peach banana apple pineapple grapfruit tomatoe ginger watermelon
Tokyo 0 0 0 500 0 0 0 0
DC 50 55 0 0 0 0 0 0
NY 0 0 0 0 0 500 0 0
Rome 0 0 0 0 90 0 0 0
SQL Statment that I used
$sql = "SELECT peach,banana,apple,pineapple,grapfruit,tomatoe,ginger,watermelon";
$sql .= " FROM TestTable2";
$sql .= " WHERE city ='NY'";
Question:
How do I loop through the array and then the variable names (aka column names) names so that
so that we get NY and Rome values of 2 and 1 for the rest. Below is my code that I have tried, not to mention it not working
foreach ($helloArray as $key =>$value){
for($i=0;$i<=odbc_num_fields($connection);$i++)
{ if (odbc_result($connection,$i) > 0) {
echo $value; }
}
}

OKay, not sure if I completely understand your question without an output sample, but I'm guessing you want:
Tokyo => 1
DC => 1
NY => 2
Rome => 2
If so, your approach is wrong. Don't pull data and then massage it, construct your SQL to return the data you want.
SELECT City, CASE WHEN grapefruit > 0 THEN 2 WHEN tomatoe > 0 THEN 2 WHEN peach > 0 THEN 1 WHEN banana > 0 THEN 1 WHEN ...
If it has to be data driven then sort your hello array by descending values and then use it to generate the SQL case conditions and return vals
-- edit --
Okay, but the code sample above, you are looping through your array as key=>value pairs. So first pass, you're on peach=>1, then you loop through every column in the return result (peach, watermelon, etc) and check it's value is greater than 0 and if it is then you output value from your array. (peach = 1)
Because there is no comparison between the fieldname and the key of the array, you are simply going to output 1 for each column while on peach, 1 for each column while on banana, etc. While I am assuming you are wanting to check if the field NAMED peach is greater than zero and if so, then output 1, and if the field named watermelon is greater than zero then output 2, you need to modify your loop. Drop the odbc_num_field and use the odbc_result syntax to specify the column name you want to retrieve. odbc_result($connection, $key) > 0.
But going by your original question it sounds like that isn't really what you are looking for, but instead want a city assigned a certain value based on the largest number returned by those field comparisons described above (NY = 2) in which case my original answer stands and you just need to use SQL to return that value for each city.

Related

PHP array has the same index for every element

I'm working on a program that prints the qualities of every individual in a team.
I have 3 tables:
The Teams table:
TeamID
1
2
The TeamPlayers table :
PlayerID
Team
100
1
269
1
357
2
The program works like this: There is a textbox in the HTML page where the user is typing the ID of the team and the program outputs the members. The problem is that each player is stored in an array. and all have the same index:
$fetchPlayersSQL = "SELECT Player_ID
FROM TeamPlayers
WHERE Team = $TeamID;";
$fetchPlayers = ibase_query($dbConnection, $fetchPlayersSQL);
while ($row2 = ibase_fetch_object($fetchPlayers)) {
$fetchPlayersArray = get_object_vars($row2);
print_r($fetchPlayersArray);
}
Keep in mind $TeamID is the value introduced by the user in the HTML textbox.
Now, this program outputs this:
Array ( [Player_ID] => 2157 )
Array ( [Player_ID] => 734 )
Array ( [Player_ID] => 2160 )
Array ( [Player_ID] => 3744 )
Array ( [Player_ID] => 2166 )
(Keep in mind, 2157, 734, 2160, 3744 and 2166 are other players, there are a lot of them, but I listed only a few)
The problem is that I need every player to have their own index in the array, because I have to print their qualities
I really can't find where the problem comes from. Maybe I am using an incorrect method to select since there are more players in a team.
The 3rd table is just the qualities of every player
PlayerID
Height
Weight
HairColor
100
187
80
black
357
167
67
grey
269
182
95
brown
And the expected output is something like this:
The user enters 1 in the HTML textbox, Team 1 players are 100 and 269 so they should see:
Array ( [0] => 2157 )
Array ( [1] => 734 )
echo $row2->Player_ID; just prints their IDs, we have player 100 and 269 in the Team 1, and this prints 100269
It might not be the most elegant solution, but you can always build that array yourself in a loop:
$a = array();
while ($row2 = ibase_fetch_object($fetchPlayers)) {
$a[] = $row2->Player_ID;
}
print_r($a);
See if that works for you, I am not able to code at the moment.

How to allow duplicate mysql row id in array?

My data in table t1 as below (only 2 record),
+-----------+-----------------+----------+
| shid | lvlmin | lvlmax |
+-----------+-----------------+----------+
| 1 | 1 | 10 |
| 2 | 5 | 10 |
+----------------------------------------+
My php code is:
$userinfo[0] = '9';
$ghunt = DB::fetch_all("SELECT shid FROM t1
WHERE lvlmin <= ".$userinfo[0]." AND lvlmax >= ".$userinfo[0].
"ORDER BY rand() LIMIT 5");
print_r($ghunt);
Result got 2 array:
Array ( [0] => Array ( [shid] => 2 ) [1] => Array ( [shid] => 1 ) )
How do I do when the array result is less than the LIMIT 5 in mysql query, auto use the array result in $ghunt to fill up the array?
What I mean is:
Array (
[0] => Array ( [shid] => 2 )
[1] => Array ( [shid] => 1 )
[2] => Array ( [shid] => 2 )
[3] => Array ( [shid] => 1 )
[4] => Array ( [shid] => 1 )
)
The shid can be random place in array.
Why don't you do something like this?
If (count($ghunt) < 5){
$realResultCount = count($ghunt);
for ($i = realResultCount; $i <= 5; $i++){
$ghunt[$i] = $ghunt[rand(0,realResultCount-1)];
}
}
Basically, what above code does is, if ghunt has less than 5 records in it, it tops it up to 5, by randomly selecting records out of initially returned records.
I don't code PHP, but I can describe one way you can achieve your goal simply. Most languages have a MOD operator, usually % - the php manual page for mod is here
It gives us the remainder of a division operation, so 10 mod 3 is 1, because 10 divided by 3 is 9 remainder 1
A useful property of MOD then, is that it always cycles between 0 and 1 less than what you're modding by. If you mod an incrementing number by 5, the result will always be 0,1,2,3,4,0,1,2,3,4 in a cycle. This means you can have a for loop with some incrementing number, mod by an array length and the result will be an integer that is certainly an array index. If the loop variable goes higher than the end of the array, the mod operator will make it wrap round to the start of the array again
MyArray[ 1746262848 mod MyArray.length ]
Will certainly not crash, even if the array only has 2 items
So for your case, just have a loop.. make he following pseudo code into PHP
// run the loop 5 times
For I as integer = 0 to 4 do
Print MyArray[ i mod MyArray.length ]
If you have 2 items in your array, A and B, it will simply print ABABA
If you have 3 items A B C it will print ABCAB
Hopefully this info will be helpful to you for implementing a solution in php for this, and many future problems. Mod can be really useful for implementing various things when working with arrays

array_combine(); not producing values properly

EDIT: Alright, my original post was kinda confusing, I've also tried something new. Here's my code:
if($_POST['submit']=='Save'){
$_SESSION['quantity'] = $_POST['quantity'];
$_SESSION['order'] = array_combine($_SESSION['parts-order'], $_SESSION['quantity']);
header("Location: shopping.php");
exit;
}
Both $_SESSION arrays are 430 long, both containing strings. When I print_r() on both $_SESSION arrays separately, they return their expected values. Basically, when I combine the arrays, I expect this output:
Array
(
[1 inch ratchet tie down] => 13
[24" White Ring Buoy w/ Reflective Tape] => 4
[50' Throw Line w/bag] => 5
[Classic Shirt Large] => 0
...
)
Y'know, or whatever values are in $_SESSION['quantity']. I, instead, get this:
Array
(
[1 inch ratchet tie down] => 0
[24" White Ring Buoy w/ Reflective Tape] => 0
[50' Throw Line w/bag] => 0
[Classic Shirt Large] => 0
...
)
Unless each of the $_SESSION['quantity'] values is the same, it produces 0. How do the values get changed to 0 in the process of array_combine?
Thanks.

Advice on list/look up table/hash table?

I have a fairly simple (at least I thought simple) task I'm trying to achieve but for the life of me I can't think of the best way of doing it in php.
Note I'm trying to avoid using nested multi-dimensional arrays.
What I want to do is a simple 2 axis reference table which I can query/look up against.
0 | 1 | 2 | 3 | 4 | 5
0 5 0 0 0 0 0
-
1 0 2 0 1 0 0
-
2 0 0 0 7 0 1
-
3 1 2 4 10 1 0
-
4 0 0 0 0 0 0
-
5 0 3 4 0 1 0
Then I want to query it so lookup_table(3,3) would return 10. I also need to update the values in the table so like add_lookup_table(3,3,1) would change location 3,3 to 11 or some variation of.
So far I know I can achieve it with multidim arrays however want to avoid this because its just going to be a pain in the ass getting and setting each time.
I thought about a list() but php's lists aren't really lists so that goes out the window.
What I'm after is suggestions/recommendations for a better way of doing this.
you can just use a single array like so
$array = array(
5, 0, 0, 0, 0, 0,
0, 2, 0, 1, 0 , 0
..etc...
);
then each key is just $array[$row * 6 + $column]
so $array[3*6 + 3]
or define your array as something like
$array["3.3"] = 10;
both of the above are BAD ways to do it when a multidimensional array exists and is well suited for the task.
you list the reason you dont want to use it as "getting and setting each time" - what ever the solution, you will have to get and set to populate it.
The real solution here seems to be the one you wish to avoid
you MAY want to check
http://php.net/manual/en/spl.datastructures.php
That has extra structures

Add extra cost per array base on key value per producto

everyone, I have the following problem I need to solve...
I'm building a shopping cart, everything was working fine until I decide to add some extras, so when you buy a product it let you add some extra items for an extra cost, so let say
Shoes $20.00 if you want to add an extra "coluor" it will cost you $10 extra...
so if you have only 1 item(one pair of shoes) it works fine, the problem is when you add an extra pair of shoes for a total of 2 items in your cart
Sport Shoes $20 + 10 per colour
Formal Shoes $30
so with that we can see that the total to be paid is only $60.00, but it shows $70.00 so why is that? what I have seen is that the next product get the extra cost from the first item, and if the next item has an extra, it get added plus the extras from the first extras of the first product... as you can see is kind of confusing.. so here is my code.
First, you need to understand how my array is build so here it is:
Normal Array for a single item:
Array
(
[cart] => Array
(
[2] => Array
(
[10] => Array
(
[quantity] => 1
[extra1] =>
[extra2] =>
)
)
)
)
So my session is that, the first ID[2] is the products ID, the second[10] is the Stock ID, the quantity and the extras... that works just fine... the problem is with the second.
Array
(
[cart] => Array
(
[2] => Array
(
[10] => Array
(
[quantity] => 1
[extra1] => Green +$10
[extra2] => Red +$10
)
)
[1] => Array
(
[7] => Array
(
[quantity] => 1
[extra1] => 0
[extra2] => 0
)
)
)
)
so that's what the session looks like, I'm able to manipulate that array in any way I need, such as, update quantity, add extras, unset product or stock and so on... also the prices with discounts are display and sum or subtracted correctly the problem are the extras... which I don't understand why I have such a hard time to manipulate...
the code that I'm using to display the information is as follow:
$s_pq = $_SESSION['cart'];
$ext1 = 0;
$ext2 = 0;
foreach ($s_pq as $kes => $values){
$qidq = $_SESSION['cart'][$kes];
foreach ($qidq as $sks => $svs ){
$ex_ex1 = $svs['extra1'];
$ex_ex2 = $svs['extra2'];
if ($ex_ex1 != '' && $ex_ex1 > 0 ) {
$extt1 += 10;
} else {$extt1 = 0;}
if ($ex_ex2 != '' && $ex_ex2 > 0 ) {
$extt2 += 10;
} else {$extt2 = 0;}
}
}
That little code is the same structure that I use to display the rest of the information:
$s_pq = $_SESSION['cart'];
foreach ($s_pq as $kes => $values){
// display product name and extra data related to that product ID
// DB Query to extract the info a few if's and echos..
$qidq = $_SESSION['cart'][$kes];
foreach ($qidq as $sks => $svs ){
// Another few DB queries to fetch information for the stock for each item
}
}
is a very simple code to work with the array from my session and is working fine, but the problem remains... so in the first code the idea is to see if the key [extra1] or [extra2] are different from " " if so it means that it has information other than " " which can be a single character but not empty and not space or zero's, if that is the case then add extra $10 if not then 0...
in another statement I use those variables $extt2 and $extt1 to add the values to the final cost
$final = round($db_price, 2) * $num_items_total + $extt1 + $extt2;
echo '$ '.$final;
with that code I display the total cost for each item in the cart.
so that is all I have for the cart session it will have nothing else but that...
last but not least here is an array for multiple size with some extras...
Array
(
[cart] => Array
(
[2] => Array
(
[10] => Array
(
[quantity] => 1
[extra1] => asdasd
[extra2] => asdasd
)
[12] => Array
(
[quantity] => 1
[extra1] =>
[extra2] =>
)
)
[1] => Array
(
[7] => Array
(
[quantity] => 1
[extra1] => as
[extra2] => asda
)
)
)
)
This is telling you that:
Name | Descr | Total
| Size 10 |
Item [2] | quantity 1 |
$20 | Extra 1 +10 | $60.00 <-- Good total
| Extra 2 +10 |
|--------------------|
| Size 12 |
| quantity 1 |
-----------------------------------------
Item [1] | quantity 1 |
$20 | Extra 1 +10 | $60.00 <-- Wrong total
| Extra 2 +10 | it should be $40.00
-----------------------------------------
Total $120.00
Thank you for taking the time, I appreciate any help you can provide!
F I X E D
I went through all my files line by line, and what i have discover was shocking! how could be so stupid!!! what happen was that I have 4 loops [loop [loop vars [loop [loop]]]] and that was the problem with the extras, the first 2 loops already show the information I need, I didn't see them because the file is damm long and I forgot about them, and the second loops I though I was outside the first 2 loops but I wasn't! and that was the problem, so I had to remove the other 2 loops and work with the first 2 loops and is working flawlessly; !! omg, 2 day!!, two day with that!! Thank you all!
So in other words, you can not use loops inside loops for the same purpose, basically was I was creating was a flood inside a loop, and for that in my case my variables never got the change to reset and that was because, the first loop was pulling the information when it was done it jump to the next key, but the loop inside was never finish so my vars never reset and that was the problem...
Again, thank you all.
Hmm its always the little things that kills code so I'll start there. I noticed that $extt1 and $extt2 are never reset in the foreach loop. This may be the source of the incrementing extra cost error. They are initialized before that loop but never reset between items.
Are you setting a default value for '$extt1' & '$extt2'? I see that you are setting:
$ext1 = 0;
$ext2 = 0;
But then you are setting:
$extt1 += 10;
And then you are totaling up all of the '$extt1' variables, but not resetting them for each loop.
So, the first time that you use it, it should be set to zero and then if it matches conditions, it will modify it. The next time you use it, since you're not setting it to zero first, '$extt1' still equals 10.
Move
$ext1 = 0;
$ext2 = 0;
inside your foreach loop
$s_pq = $_SESSION['cart'];
foreach ($s_pq as $kes => $values){
$ext1 = 0;
$ext2 = 0;
$qidq = $_SESSION['cart'][$kes];
foreach ($qidq as $sks => $svs ){
$ex_ex1 = $svs['extra1'];
$ex_ex2 = $svs['extra2'];
if ($ex_ex1 != '' && $ex_ex1 > 0 ) {
$extt1 += 10;
} else {$extt1 = 0;}
if ($ex_ex2 != '' && $ex_ex2 > 0 ) {
$extt2 += 10;
} else {$extt2 = 0;}
}
}

Categories