PHP setting and looping associative array - php

I populate the $_SESSION['products'] array from a file:
$myFile = '.\products.txt';
$handle = fopen($myFile, 'r');
while (!feof($handle))
{
$prod = explode('|', fgets($handle));
$_SESSION['products'] = array($prod[4] => array(
'name' => $prod[0],
'price' => $prod[1],
'description' => $prod[2],
'image' => $prod[3]));
}
Then I want to loop through it, printing all the names and prices:
foreach ($_SESSION['products'] as $prodID=>$value) {
echo $_SESSION['products'][$value]['name'];
echo $_SESSION['products'][$value]['price'];
}
But it doesn't seem to work!

You need to check again how the foreach works. In your case, you can simply do the following:
foreach($_SESSION['products'] as $value) {
echo $value['name'];
echo $value['price'];
}

Your problem is, here you are overwriting the products array with every product, which means there will only ever be the last product present:
$_SESSION['products'] = array($prod[4] => array(
Try appending to the array like:
$_SESSION['products'][$prod[4]] = array(
// ^^^^^^^^ set the key as the product ID here
'name' => $prod[0],
'price' => $prod[1],
'description' => $prod[2],
'image' => $prod[3]);
Also your foreach is wrong, try
foreach ($_SESSION['products'] as $prodID=>$value) {
echo $value['name'];
echo $value['price'];
}

foreach ($_SESSION['products'] as $prodID=>$value) {
echo $_SESSION['products'][$prodID]['name'];
echo $_SESSION['products'][$prodID]['price'];
}

Related

PHP in_array not working after loop in session

I have a foreach loop to check all array of ID and if using in_array to see if any of the arrays of IDsis equaled my $_POST['id'] as shown below:
$cart = array (
'title' => $_POST['title'],
'price' => $_POST['price'],
'img_src' => $_POST['img_src'],
'id' => $_POST['id'],
);
foreach ($_SESSION['cart'] as $item) {
$id = $item['id'];
}
if(in_array($_POST['id'], $id)){
echo "ID exist";
}else{
$_SESSION['cart'][] = $cart;
$count = count($_SESSION["cart"]);
}
For some reason, it keeps adding even when the ID exist inside the list of arrays of IDs.
You are just changing the value of $id inside foreach loop. Try to store value in array. Refer the below code:
$cart = array (
'title' => $_POST['title'],
'price' => $_POST['price'],
'img_src' => $_POST['img_src'],
'id' => $_POST['id'],
);
$id = array();
foreach ($_SESSION['cart'] as $item) {
$id[] = $item['id'];
}
if(in_array($_POST['id'], $id)){
echo "ID exist";
}else{
$_SESSION['cart'][] = $cart;
$count = count($_SESSION["cart"]);
}

update batch in codeigniter

I have data on db_temporary here I will update based on id_service, but why doesn't the update work?
public function updateUpload() {
$db = $this->M_order->db_temporary_service(); //db_temporary
$data = array();
foreach($db AS $key => $val){
$data[] = array(
"id_service" => $_POST['id_service'][$key],
"id_destination" => $_POST['id_destination'][$key],
"id_sub_destination" => $_POST['id_sub_destination'][$key],
"charges_order" => $_POST['charges_order'][$key],
"weight_order" => $_POST['weight_order'][$key],
"jenis_service" => $_POST['jenis_service'][$key],
"service_order" => $_POST['service_order'][$key],
"charges_order" => $_POST['charges_order'][$key],
);
echo '<pre>', print_r($data);
//update to db_service where id_service
$this->db->update_batch('service', $data, 'id_service');
redirect('backend/.....');
}
}
The data doesn't seem to be updated because you've used update_batch as well as redirect inside foreach loop, I'm writing the rectified code below, comments are mentioned wherever necessary. See if it resolves your issue.
public function updateUpload(){
$db = $this->M_order->db_temporary_service(); //db_temporary
$data = array();
foreach($db AS $key => $val){
$data[] = array(
"id_service" => $_POST['id_service'][$key],
"id_destination" => $_POST['id_destination'][$key],
"id_sub_destination" => $_POST['id_sub_destination'][$key],
"charges_order" => $_POST['charges_order'][$key],
"weight_order" => $_POST['weight_order'][$key],
"jenis_service" => $_POST['jenis_service'][$key],
"service_order" => $_POST['service_order'][$key],
"charges_order" => $_POST['charges_order'][$key],
);
}
// echo '<pre>', print_r($data); // all the data should be here
$this->db->update_batch('service', $data, 'id_service'); // update the table with all the data
redirect('backend/.....');
}

How to display the value of array as string or text not as index value

I have two table one for sections where each section has many questions when i echo i got the section text but the questions as index value 0 1 2
<?php
$result = mysql_query($query);
if ($result) {
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[($row['SECTION_NAME'])][][($row['QUES_TEXT'])][] = array(
'SECTION' => $row['SECTION_NAME'],
'QUESTION' => $row['QUES_TEXT']
);
}
foreach ($data as $SECTION => $QUESTIONS) {
echo '<h2>',htmlentities($SECTION),'</h2>';
foreach ($QUESTIONS as $QUESTIONS_TEXT => $TEXT) {
echo '<h2>',($QUESTIONS_TEXT),'</h2>';
}
}
}
?>
You are creating extra nested arrays and also the parens are unneeded:
$data[$row['SECTION_NAME']][][$row['QUES_TEXT']][] = array(
'SECTION' => $row['SECTION_NAME'],
'QUESTION' => $row['QUES_TEXT']
);
Should be:
if (empty($data[$row['SECTION_NAME']]) {
$data[$row['SECTION_NAME']] = array();
}
$data[$row['SECTION_NAME']][$row['QUES_TEXT']] = array(
'SECTION' => $row['SECTION_NAME'],
'QUESTION' => $row['QUES_TEXT']
);
Also please see the comments to your original question, this is no longer a safe way to use MySQL from PHP.

Array ksort only shows non-like values?

Have an array for a ranking script.
Some times the key will be the same. They are numeric.
When the sort is ran, only non-like values are echoed.
Can't figure out the fix.
$list = array( $value1 => 'text', $value2 => 'text', $value3 => 'text');
krsort($list);
foreach ($list as $key => $frame) {
echo $frame;
}
If you assign two values to the same key in an array, the first value will be overridden by the second. You'll therefore end up with only one value for that key in the array.
To resolve this, I'd suggest to change your array structure like this:
<?php
$list = array( $key1 => array($key1member1, $key2member2),
$key2 => array($key2member1),
$key3 => array($key3member1, $key3member2, $key3member3) );
krsort($list);
foreach ($list as $key => $frames) {
foreach ($frames => $frame) {
echo $frame;
}
}
?>
Going by what you wrote in the comments to this question and my other answer, I'd recommend to switch keys and values.
<?php
$list = array( "frame1" => 4, "frame2" => 2, "frame3" => 99, "frame4" => 42 );
arsort($list);
foreach ($list as $frame => $ranking) {
echo $frame;
}
?>

PHP While loop array

Any help is appreciated.
I have an array that is forfetch like this. The reason is to brake down a product in individual arrays. However I can not figure out what statement to put in the while loop so i can loop through each array in $row. initially the statement should be
while ($row = mysql_fetch_assoc($result))
however this was already done to be able to sort the array.
$sorted = array_orderby($newarray, 'volume', SORT_DESC, 'edition', SORT_ASC);
foreach($sorted as $row)
{
while( ??????? )
{
$row = build_items($row);
$template->assign_block_vars('featured_items', array(
'ID' => $row['id'],
'IMAGE' => $row['pict_url'],
'TITLE' => $row['title'],
'SUBTITLE' => $row['subtitle'],
'BUY_NOW' => ($difference < 0) ? '' : $row['buy_now'],
'B_BOLD' => ($row['bold'] == 'y')
));
$k++;
$feat_items = true;
}
}
Just found the answer. Sorry guys im new at PHP.
foreach($sorted AS $row) {
$row = build_items($row);
// time left till the end of this auction
$s_difference = time() - $row['starts'];
$difference = $row['ends'] - time();
$bgcolour = ($k % 2) ? 'bgcolor="#FFFEEE"' : '';
$template->assign_block_vars('featured_items', array(
'ID' => $row['id'],
'IMAGE' => $row['pict_url'],
'TITLE' => $row['title'],
'SUBTITLE' => $row['subtitle'],
'BUY_NOW' => ($difference < 0) ? '' : $row['buy_now'],
'BID' => $row['current_bid'],
'BIDFORM' => $system->print_money($row['current_bid']),
'TIMELEFT' => FormatTimeLeft($difference),
'NUMBIDS' => $row['num_bids'],
'B_BOLD' => ($row['bold'] == 'y')
));
$k++;
$feat_items = true;
}
foreach($sorted AS $rows) {
foreach($rows AS $row) {
...
}
}
or with keys/indices
foreach($sorted AS $key => $rows) {
foreach($rows AS $index => $row) {
Yes.., we can use foreach to print all the values in an array.
Example: I have an array called "data" (SQLITE dynamic data). I want to print all the values which are there on "data" array.
By using following sample code we can print the values in a table format.
foreach ($data as $item) {
$date = $item['date'];
$url = $item['url'];
$name = $item['name'];
echo"
<tr>
<td>$date</td>
<td>$name</td>
<td>$url</td>
</tr>
";
}
Please let me know if i did any mistakes here, sorry for my bad English.

Categories