multidimensional array with unknow key's - php

I'm having a multidimensional array from which I don't know the keys and I need all key's with their value.
My array is database filled:
$rows[$product_id][$productgroup_id] = $amount
So the array is for example filled with 2 products:
$rows[108][3] = 2
$rows[2][5] = 4
So my array now holds 2 product:
Product_id 108 from productgroup 3 with an amount of 2
Product_id 2 from productgroup 5 with an amount of 4
Now I need to walk through the array and I need the keys and the amount. So I'm thinking in a foreach loop
foreach($rows as $row){
foreach($row as $key => $value){
echo "Key:".$key." Value: ".$value."<br>";"
}
}
But this only echo's the first key, product_id and the amount. But I need the product_id, productgroup_id and the amount. So how do I also get the productgroup_id?

the code you have so far is almost there, you simply need to extract both id's with the foreach loop.
foreach($rows as $product_id => $group){
foreach($group as $productgroup_id => $value){
echo "Product ID:" . $product_id . " Group:".$productgroup_id." Value: ".$value."<br>";"
}
}

If you want to see/debug the array, you could use the php function print_r(), in your case, it will be echo print_r($row).

Related

UPDATE statement with associative array in PHP returns Notice

I have a problem updating my table with data loaded from Excel sheet into associative array, here is my snippet:
foreach ($priceList as $sku => $price) {
$stmt = $dbh->prepare("UPDATE product SET price = :price WHERE sku = :sku;");
$stmt->bindParam(':price', $price);
$stmt->bindParam(':sku', $sku);
$stmt->execute();
echo 'Table has been updated...';
}
After executing, the prices in the table won't update and I get a notice: "Notice: Array to string conversion..."
var_dump of my array:
array (size=1768)
'32732eglo' => string '27.25' (length=5)
The sku column in my table is VARCHAR and the price column is DECIMAL, what am I doing wrong?
From your sample output it looks as though you have an extra layer of array...
array (size=1) 0 =>
array (size=1768)
'32732eglo' => string '2...
so use...
foreach ($priceList[0] as $sku => $price) {
So I had an array within array which happened by using
$priceList[] = array_combine($skuArray,$pricesArray);
I fixed it by declaring the array before this row:
$priceList = array();
$priceList = array_combine($skuArray,$pricesArray);
or simply in one line:
$priceList = array_combine($skuArray,$pricesArray);

Printing out associative arrays fetched from SQL database

I have fetched 3 arrays out of a database and put them in associative arrays.
I have learned to print out array as shown below in the comments, but this doesn't seem to work? How can I achieve this?
while($row = mysql_fetch_array($query)) //fetching row in db
{
$weight = $row['weight'];
$height = $row['height'];
$bmi = round($weight / (pow(($height/100),2)),2); //calculates bmi
$arrName[] = $row['name']; //main name array
$arrGender[] = array($row['name'] => $row['gender']); //this and below are associative arrays
$arrBmi[] = array($row['name'] => $bmi);
}
foreach($arrName as $key=>$value){
echo "$value is of gender {$arrGender[$value]} and has a bmi of {$arrBmi[$value]}"; //this line
}
Like this instead:
$arrGender[$row['name']] = $row['gender']
$arrBmi[$row['name']] = $bmi);
The way you're doing it, you're assigning multiple sub-arrays to numeric indexes instead of using the name as the key. One thing to watch out for if you end up doing it this way is that if there are non-unique names in your query result, the value at that array key will be overwritten for subsequent duplicate names.
It doesn't look like your really need the second loop, though. You can output the same thing in the while loop as you fetch the results:
while ($row = mysql_fetch_array($query)) //fetching row in db
{
$bmi = round( $row['weight'] / (pow(( $row['height'] /100),2)),2); //calculates bmi
echo "$row[name] is of gender $row[gender] and has a bmi of $bmi"; //this line
}
This is a weird array to construct and I would simplify it, but use the $key and the name ($value) to access the others:
echo "$value is of gender {$arrGender[$key][$value]}
and has a bmi of {$arrBmi[$key][$value]}";
To keep it simple just use the array as it comes from the fetch:
$array[] = ['name' => $row['name'],
'gender' => $row['gender'],
'bmi' => $bmi];
Then in the loop:
echo "{$value['name']} is of gender {$value['gender']}
and has a bmi of {$value['bmi']}";

PHP json_encode returning single row only

So I have an associative array $_SESSION['cart_items']) This is the current output when I print_r($_SESSION['cart_items']):
Array
(
[3] => 23
[5] => 5
[4] => 1
)
In the output above, the first one for example [3]=>23 where [3] is the id and 23 is the quantity I entered from a form:
My current data:
Note that in the image above, the quantity column is different from the quantity I'm entering from a form.
So far this is the code I've tried:
$statement = $conn->query("SELECT id, name, price, quantity FROM product WHERE id IN (".implode(',',$_SESSION['cart_items']).")");
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
print json_encode($data);
And this is the output:
[{"id":"5","name":"ballpen","price":"23","quantity":"13"}]
As you can see it works, though I only get a single row which should be three.
Is there something wrong with my query?
You show that the array keys in the session array match the ids in the database. implode() implodes/joins the values in the array. So you need to implode the keys:
implode(',', array_keys($_SESSION['cart_items']))
Or flip the array:
implode(',', array_flip($_SESSION['cart_items']))

Drupal 6 $key => $value form #options array built using while loop where $key = $value

I'm trying to build an array of $key => $values using a while loop where the $key is equal to the value, from a db_query. I think the syntax isn't correct
function _form(){
$person = db_query("SELECT name FROM {person}");
$columnValues = Array();
while ($row = db_fetch_array($person) ) {
$columnValues[] = array($row['name']=> $row['name']);
}
.
.
.
I have a few questions.
do i need to create a key to pull out the actual 'select' menu item value?
if i need to create a key, is there a way in the while loop to not create a new array for each element that is keyed by its same value (eg. apple => apple)
what is the correct way to pull out values from checkboxes and from select so i get a string and not an ordered number? (eg. form_values['value']['select_name'] , form_values['value']['checkboxes_name'] so that first returns selected item 'apple' and second gives checked item 'apple'.) ... i like apples.
You seem to be making a mistake here - in the key value pair, the value cannot be an array
while ($row = db_fetch_array($person) ) {
$columnValues[] = array($row['name']=> $row['name']);
}
should be
while ($row = db_fetch_array($person) ) {
$columnValues[$row['name']] = $row['name'];
}
Answers:
Yes, you should always add a key value pair - as value is what gets displayed and key is what gets submitted in the form submit.
Yes the above explains how you should create key => value pair and not an array of key => value pairs for each item.
Individual checkbox items have values and you can set the value of checkbox to be the same as that of the display.

Looping through a 2d session array shopping cart php

Im buliding a shopping cart and want to use a 2d array to store the items ID and quantity. When the user goes to the shopping cart I want to be able to grab the Items ID from the array and output the items details from the database
/**************** Adding to the 2d array ***********************/
//Check to see if variable isset and then add item to shopping cart
//$itemID is the ID of the product
//$quantity is the quantity of the product they wish to order
if(isset($_GET['add'])){
$itemID = $_GET['add'];
$quantity = $_POST['quantity'];
$_SESSION['cart'][] = array("id" => $itemID,"quantity" => $quantity);
header('xxx');//stops user contsanlty adding on refresh
}
/******************** Looping through the array **********************/
//need to loop through grab the item ID
//then pull what we need from the database
//This is where I want to grab the id from the array and query the database
$cart = $_SESSION['cart'];
foreach ($cart as $value ){
//works like it should
foreach ( $value as $key=> $final_val ){
echo $key;
echo ':';
echo $final_val;
echo '<br/>';
}
echo '<br/>';
}
The array outputs like so
id:1
quantity:5
id:2
quantity:1
Im having a little trouble figuring out how to seperate the ID and quantity so that I can query the database with the item ID.
foreach ( $value as $key=> $final_val ){
if($key=='id')
{
echo $key;
echo ':';
echo $final_val;
echo '<br/>';
}
}
or you can directly use like $value['id']
something like this will help you..please try.
is this you need?

Categories