PHP - Adding Items In Array
I have an array of products. The array has an ID and price. I'd like to know the most efficient way of adding up all the same ID fields in the array.
Code: [Select] <?php $items[] = array( 'id' => 1, 'price' => 5.99, ); $items[] = array( 'id' => 2, 'price' => 1.99, ); $items[] = array( 'id' => 3, 'price' => 2.40, ); $items[] = array( 'id' => 2, 'price' => 6.99, ); $items[] = array( 'id' => 4, 'price' => 8, ); $items[] = array( 'id' => 2, 'price' => 3, ); $items[] = array( 'id' => 3, 'price' => 1, ); function add_like_items($items) { //manipulation return $sums; } //$sums would be an array like //$sum[1] = 5.99 //$sum[2] = 11.98 //$sum[3] = 3.40 //$sum[4] = 8 ?> Anybody have suggestions on the best way to go about doing this? Similar TutorialsHi, Im trying to learn how to build a shopping cart system, im have a few problems and im not sure where im going wrong, it looks as though im getting an item into the session, but it looks like when i add another it over writing the first one, and im having trouble trying to echo it out. Here is what i have atm Code: [Select] session_start(); include('functions.php'); $pid = $_GET['product']; $q = $_GET['qty']; if($_GET['function']=="add") { echo "add " . $_GET['product']; $_SESSION['cart']=array(); $_SESSION['cart']['productid']=$pid; $_SESSION['cart']['qty']=$q; } print_r($_SESSION['cart']); echo showCart(); Am i way off on my code? regardless of how many things i try to add to session, all i can print out is the last one i entered. Cheers hello all, I was hoping someone could help me figure out how to add sizes to my shopping cart. Right now the items add just fine. The site sells shirts and I'm having trouble displaying the sizes once selected and added to the cart. It will post the size selected, but if the customer tries to add another shirt the size will overwrite the last. Any help is appreciated. Heres how I add items to the cart... Code: [Select] session_start(); // Process actions $cart = $_SESSION['cart']; $action = $_GET['action']; switch ($action) { case 'empty': if($cart) { unset($cart); } break; case 'add': if ($cart) { $cart .= ','.$_GET['product_id']; } else { $cart = $_GET['product_id']; } break; The form with the size selection and add to cart button.. Code: [Select] <form action="cart.php?action=add&product_id=<?php echo $row_rs_products['product_id'] ?>" method="POST" name="addcart" id="addcart"> <table width="300" border="0"> <tr> <td><label for="sizes"></label> <select name="product_size" id="product_size" title="<?php echo $row_rs_products['product_size']; ?>"> <?php do { ?> <?php } while ($row_rs_sizes = mysql_fetch_assoc($rs_sizes)); $rows = mysql_num_rows($rs_sizes); if($rows > 0) { mysql_data_seek($rs_sizes, 0); $row_rs_sizes = mysql_fetch_assoc($rs_sizes); } ?> </select></td> <td><input type="submit" name="submit" id="submit" value="add to cart"> function displaying the cart.. Code: [Select] function showCart() { global $db; $cart = $_SESSION['cart']; if ($cart) { $items = explode(',',$cart); $contents = array(); foreach ($items as $item) { $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; } $output[] = '<form action="cart.php?action=update" method="post" id="cart">'; $output[] = '<table>'; // start div $output[] = '<div id="cart_table">'; // $output[] = '<tr>'; $output[] = '<td><h4>Product</h4></td>'; $output[] = '<td><h4>Item No.</h4></td>'; $output[] = '<td><h4>Price</h4></td>'; $output[] = '<td><h4>Size</h4></td>'; $output[] = '<td><h4>Quantity</h4></td>'; $output[] = '<td><h4>Price Total</h4></td>'; $output[] = '<td><h4> </h4></td>'; $output[] = '</tr>'; //new row foreach ($contents as $product_id=>$qty) { $sql = 'SELECT * FROM products WHERE product_id = '.$product_id; $result = $db->query($sql); $row = $result->fetch(); extract($row); // $output[] = '<tr>'; $output[] = '<td><a href="product.php?product_id='.$product_id.'">'.$product_title.'</a></td>'; $output[] = '<td>'.$product_plu.'</td>'; $output[] = '<td>$'.$product_price.'</td>'; // //$output[] = '<td>'.$product_size.'</td>'; $output[] = '<td>'.$_POST['product_size'].'</td>'; // $output[] = '<td><input type="text" name="qty'.$product_id.'" value="'.$qty.'" size="3" maxlength="3" /></td>'; $output[] = '<td>X $'.($product_price * $qty).'</td>'; $total += $product_price * $qty; $output[] = '<td><a href="cart.php?action=delete&product_id='.$product_id.'" class="r">Remove</a> </td>'; $output[] = '</tr>'; //end div $output[] = '</div>'; } $output[] = '</table>'; $output[] = '<p>Grand total: <strong>$'.$total.'</strong></p>'; $output[] = '<div class="float-right"><button type="submit">Update cart</button>'; $output[] = '</form>'; Hi I have an array of items that I am currently displaying a foreach loop What I'm looking to do, is add a string, to all of items, a part from the last 4: foreach ($pager->getResults() as $items => $item) { echo $item->getName(); //need to add a string to this for the all but the last 4 } Thanks Hi, I'm hoping someone can help me with a simply array problem. I have a table with two columns: "ID" and "Name" and 100 Names. I also have an array called $myIDList containing 10 IDs. I want to display 10 Names from the table that correspond with the IDs from my array. Originally, I tried to implode the array, adding commas and inserted into my MySQL query using: $myQuery = "SELECT ID, Name FROM namesTable WHERE ID IN ($myImplodedIDList)"; The problem was that duplicated names (i.e. the same Name, but assiged to different IDs) would only be displayed once. So now I'm trying to use the original array to loop through a second array and display Names where the ID matches an ID from my first array. I have succesffuly listed the table like this: $myQuery = "SELECT ID, Name FROM myTable ORDER BY ID"; $myResult = mysql_query($myQuery) or die(mysql_error()); while($row=mysql_fetch_array($myResult)) { echo $row['ID']; echo $row['Name']; } But I want to do something like: while($row=mysql_fetch_array($myResult)) { while $row['ID'] = $myIDList { echo $row['Name'] } } Can someone shed some light onto this for me please? Thank you! Bryan How can I check if an array contains two items that are the same? For example ("apples", "bananas", "oranges") returns false But ("apples", "bananas", "bananas") returns true Hi guys, I'm just working on a script to get menu items from a database, sorted by a sort column. Each item needs to be checked to see if it has a parent, then paired with the parent. Would it be best to get all of the items at once and pair them with PHP, or get the children of each item when as a separate array? id label link parent sort 1 Home index.php 0 10 2 About about.php 0 20 3 Contact Us contact.php 2 10 Running a simple query: SELECT team, rank from table ORDER BY rank ASC returns 8 records in order from 1 to 8 I then want to a assign a new variable to each that I can use for later queries ie: team with rank 1 = $team1 team with rank 2 = $team2 team with rank 3 = $team3 etc.... Thanks in advance. Hi all, I have a table that shows data from an xml response that has been converted to an array. I have successfully managed to get that to work but it's showing more items than I want. I'm trying to isolate the items by state. There are 11 or so different states, of which I only want 7. I've tried the following with a while loop but I keep getting the message "undefined index: job_status" Here's my code (partial) $projects = array(); $xml=simplexml_load_string($response) or die("Error: Cannot create object"); foreach($xml->Jobs->Job as $item) { $projects[] = array( 'job_no' => (string)$item->ID, 'job_name' => (string)$item->Name, 'job_due' => (string)$item->DueDate, 'job_status' => (string)$item->State, 'job_staff' => (string)$item->Assigned->Staff->Name, ); } usort($projects, function($a,$b) {return $a['job_due'] <=> $b['job_due']; } ); $projects = array_reverse($projects); while ($projects['job_status'] == ('Feasibility') && ('Measure Up') && ('Model Drawing') && ('Concept Design') && ('Developed Design') && ('Resource Consent') && ('Construction Documentation')) { foreach ($projects as $proj) { $formatted = date('d/m/Y', strtotime($proj['job_due'])); $job_no ="{$proj['job_no']}"; $job_name ="{$proj['job_name']}"; $job_due ="$formatted"; $job_status ="{$proj['job_status']}"; $job_staff ="{$proj['job_staff']}"; Any help would be much appreciated thanks. Hi, Im wondering if there is an easy way to get items out of an array returned by a function inside a class. A code example would be: Code: [Select] class modDB { public function getPwdSalt() { $arr = array("salt", "password"); return $arr; } } ?> And what i would like to be able to do is something like: Code: [Select] $modDB = new modDB; echo $modDB->getPwdSalt()->[1]; and just get returned 'password'. Is something like that possible? Many Thanks. Using curl_multi, I have loaded up 3 url's and then printed the array. 1) How can I also set a timestamp on output to let me know when each url was run? 2) How can I explode the array to only display the data and timestamp, excluding the text "Array ( =>", "[1] =>", "[2] =>" and " )"? Code <?php function multiRequest($data, $options = array()) { // array of curl handles $curly = array(); // data to be returned $result = array(); // multi handle $mh = curl_multi_init(); // loop through $data and create curl handles // then add them to the multi-handle foreach ($data as $id => $d) { $curly[$id] = curl_init(); $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d; curl_setopt($curly[$id], CURLOPT_URL, $url); curl_setopt($curly[$id], CURLOPT_HEADER, 0); curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1); // post? if (is_array($d)) { if (!empty($d['post'])) { curl_setopt($curly[$id], CURLOPT_POST, 1); curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']); } } // extra options? if (!empty($options)) { curl_setopt_array($curly[$id], $options); } curl_multi_add_handle($mh, $curly[$id]); } // execute the handles $running = null; do { curl_multi_exec($mh, $running); } while($running > 0); // get content and remove handles foreach($curly as $id => $c) { $result[$id] = curl_multi_getcontent($c); curl_multi_remove_handle($mh, $c); } // all done curl_multi_close($mh); return $result; } $data = array(array(),array()); $data[0]['url'] = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Pearl+Jam&output=json'; $data[1]['url'] = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Black+Eyed+Peas&output=json'; $data[2]['url'] = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Nirvana&output=json'; $r = multiRequest($data); print_r($r); ?> Output Array ( => Pearl Jam [1] => Black Eyed Peas [2] => Nirvana ) Preferred Output 01:00:01 Pearl Jam 01:00:02 Black Eyed Peas 01:00:03 Nirvana I'm new at PHP and have a problem. I have a MySql database with lists of students grouped into classrooms. A typical group is shown in the attached screenshot screenshot.docx. I want to be able to select one or more of the names by using the associated checkbox, and upgrade a student or students into a different group as defined in the radio button list also in the screenshot. I have the rudiments of the file attached, but I have absolutely no idea how I can post the array so that the records are updated. Each student has an individual record with a field name userGroup which holds a string nominated by their classroom teacher, such as "year7", "year 8" and so on while they are in one of the several classrooms, but when they leave school this is recorded in a field named noGroup with a value of 0 or 1. I can post further details as required, but it would be great if someone could help me. -First I want to say that I love this site and always check google before I submit questions but im lost. I'm into security and trying to learn a little Apache, Mysql, and PHP to understand the development cycle better. As practice im creating a notecard test review site. Create notecard Decks, add/delete questions etc. shuffle, then test yourself. I though I was doing good until I got to the page that shows the questions (test.php). Right now I pass the "deck_id" field in a GET to a "test.php?id=" page that runs a script that pulls out all the questions for that deck from my "questions" table and loops to show each question for that "deck". My loop works, (gets array from database and shows questions one by one), but it writes all the questions to the page at the same time. DUH. I want it to show one question with a "NEXT" button to show next question. This button clears the first question and writes the next one until they are all done. No grading or anything needed. Is there a way to do this gracefully? I dont know much javascript but looked up innerHTML and see i can update text that way but the PHP loop I have goes so fast it just end up showing the last question with no way to pause it between questions. Can anyone think of a way to do this? My problem is passing the data from page to page to page (I lose the array data) If this is impossible my other thoughts a 1) store current list of Q/A's in cookie (OR) 2) pass Q/A to another page with POSTS (OR) 3)store Q/A's to temporary sql table and use GETS in loop to show each one by one. "testing.php?question=1" 4) can i set a global variable that can pass the data to separate pages? 5)user iFrame so it looks like one page (dont know how) Im leaning to number 3 but want to hear your suggestions. (sorry very new) I have this array of items in my php file.
$items = array( array("id" => 100,"categorypath" => "level1/powders", "product" => "Mens powder"), array("id" => 200,"categorypath" => "level1/oils/sunflower", "product" => "XYZ oil"), array("id" => 300,"categorypath" => "level1/eatable/vegetables", "product" => "carrot"), array("id" => 400,"categorypath" => "level1/oils/sunflower", "product" => "ABC oil"), array("id" => 500,"categorypath" => "level1/eatable/fruits", "product" => "mango"), array("id" => 600,"categorypath" => "level1/eatable/vegetables", "product" => "spinach"), array("id" => 700,"categorypath" => "level2/baby items/toys", "product" => "puzzle block"), array("id" => 800,"categorypath" => "level2/baby items/toys", "product" => "trucks and cars"), array("id" => 900,"categorypath" => "level2/baby items/clothes", "product" => "shirts"), array("id" => 1000,"categorypath" => "level1/powders", "product" => "Womens powder"), array("id" => 1100,"categorypath" => "level1/oils/groundnut", "product" => "GN oil"), ); Using the above array I am trying to generate a JSON file that will have the following structu
{ "category":[ { "categoryName":"level1", "category":[ { "categoryName":"powders", "products":[ { "id":"100", "path":"level1/powders", "prodname":"Mens powder" }, { "id":"1000", "path":"level1/powders", "prodname":"Womens powder" } ] }, { "categoryName":"oils", "category":[ { "categoryName":"sunflower", "products":[ { "id":"200", "path":"level1/oils/sunflower", "prodname":"XYZ oil" }, { "id":"400", "path":"level1/oils/sunflower", "prodname":"ABC oil" } ] }, { "categoryName":"groundnut", "products":[ { "id":"1100", "path":"level1/oils/groundnut", "prodname":"GN oil" } ] } ] }, { "categoryName":"eatable", "category":[ { "categoryName":"vegetables", "products":[ { "id":"300", "path":"level1/eatable/vegetables", "prodname":"carrot" }, { "id":"600", "path":"level1/eatable/vegetables", "prodname":"spinach" } ] }, { "categoryName":"fruits", "products":[ { "id":"500", "path":"level1/eatable/fruits", "prodname":"mango" } ] } ] } }, { "categoryName":"level2", "category":[ { "categoryName":"baby items", "category":[ { "categoryName":"toys", "products":[ { "id":"700", "path":"level2/baby items/toys", "prodname":"puzzle blocks" }, { "id":"800", "path":"level2/baby items/toys", "prodname":"trucks and cars" } ] }, { "categoryName":"clothes", "products":[ { "id":"900", "path":"level2/baby items/clothes", "prodname":"shirts" } ] } ] } ] } Not being an expert in php, I have somehow managed to reach thus far in my code, but can not quite arrive at the correct logic. Having trouble with handling associative arrays and objects in php. (Javascripting is much easier I feel) So far I have managed to fix all the errors/warning in my code. Here is my full php code:
$items = array( array("id" => 100,"categorypath" => "level1/powders", "product" => "Mens powder"), array("id" => 200,"categorypath" => "level1/oils/sunflower", "product" => "XYZ oil"), array("id" => 300,"categorypath" => "level1/eatable/vegetables", "product" => "carrot"), array("id" => 400,"categorypath" => "level1/oils/sunflower", "product" => "ABC oil"), array("id" => 500,"categorypath" => "level1/eatable/fruits", "product" => "mango"), array("id" => 600,"categorypath" => "level1/eatable/vegetables", "product" => "spinach"), array("id" => 700,"categorypath" => "level2/baby items/toys", "product" => "puzzle block"), array("id" => 800,"categorypath" => "level2/baby items/toys", "product" => "trucks and cars"), array("id" => 900,"categorypath" => "level2/baby items/clothes", "product" => "shirts"), array("id" => 1000,"categorypath" => "level1/powders", "product" => "Womens powder"), array("id" => 1100,"categorypath" => "level1/oils/groundnut", "product" => "GN oil"), ); $jsonStruct = array(); function jsonCreateStruct(){ GLOBAL $items; for($c=0; $c<count($items); $c++){ $categ = $items[$c]["categorypath"]; insertJson($categ, $items[$c]); } } function insertJson($catg, $itm){ GLOBAL $jsonStruct; $exp = explode("/",$catg); print_r("\n\n\n $catg \n"); if(count($exp) == 1){ print_r("Level 1 \n"); if(!isset($jsonStruct[0])){ $jsonStruct[0]["categoryName"] = $exp[0]; $jsonStruct[0]["products"] = array($itm); print_r("\nCreated:: $exp[0]"); }else{ $notFound = true; for($j=0; $j<count($jsonStruct); $j++){ $catgName = $jsonStruct[$j]["categoryName"]; print_r("\nFound: $catgName"); if($catgName == $exp[0]){ $notFound = false; if($jsonStruct[$j]["products"]){ array_push($jsonStruct[$j]["products"],array($itm)); }else{ $jsonStruct[$j]["products"] = array(); array_push($jsonStruct[$j]["products"],array($itm)); } } } if($notFound){ print_r("\nNotFound\n"); array_push($jsonStruct,array("categoryName"=> $exp[0], "products" => array($itm))); } } } if(count($exp) == 2){ print_r("Level 2 \n"); if(!isset($jsonStruct[0])){ $jsonStruct[0]["categoryName"] = $exp[0]; $jsonStruct[0]["categorypath"] = array("categoryName" => $exp[1], "products" => array($itm)); print_r("\nCreated:: $exp[0] / $exp[1]"); }else{ $notFound1 = true; $notFound2 = true; $indexLevel = null; for($j=0; $j<count($jsonStruct); $j++){ $catgName1 = $jsonStruct[$j]["categoryName"]; print_r("\nFound: $catgName1"); if($catgName1 == $exp[0]){ $notFound1 = false; $indexLevel = $j; if(isset($jsonStruct[$j]["categorypath"])){ $level1 = $jsonStruct[$j]["categorypath"]; for($m=0; $m<count($level1); $m++){ if(isset($level1[$m]["categoryName"])){ $catgName2 = $level1[$m]["categoryName"]; print_r("\nFound: $catgName2"); if($catgName2 == $exp[1]){ $notFound2 = false; if($level1[$m]["products"]){ array_push($jsonStruct[$j]["categorypath"][$m]["products"],array($itm)); }else{ $jsonStruct[$j]["categorypath"][$m]["products"] = array(); array_push($jsonStruct[$j]["categorypath"][$m]["products"],array($itm)); } } } } } } } if($notFound1){ print_r("\nNotFound1\n"); array_push($jsonStruct,array("categoryName"=> $exp[0], "categorypath" => array("categoryName" => $exp[1],"products" => array($itm)))); }else if($notFound2){ print_r("\nNotFound2\n"); // $jsonStruct[$indexLevel]["categorypath"] = array("categoryName"=> $exp[1], "products" => array($itm)); $jsonStruct[$indexLevel]["categorypath"] = array(); array_push($jsonStruct[$indexLevel]["categorypath"], array("categoryName"=> $exp[1], "products" => array($itm))); } } } if(count($exp) == 3){ print_r("Level 3 \n"); if(!isset($jsonStruct[0])){ $jsonStruct[0]["categoryName"] = $exp[0]; $jsonStruct[0]["categorypath"] = array("categoryName" => $exp[1], "categorypath" => array("categoryName" => $exp[2], "products" => array($itm))); print_r("\nCreated:: $exp[0] / $exp[1] / $exp[2]"); }else{ $notFound1 = true; $notFound2 = true; $notFound3 = true; $indexLevel1 = null; $indexLevel2 = null; for($j=0; $j<count($jsonStruct); $j++){ $catgName1 = $jsonStruct[$j]["categoryName"]; print_r("\nFound: $catgName1"); if($catgName1 == $exp[0]){ $notFound1 = false; $indexLevel1 = $j; if(isset($jsonStruct[$j]["categorypath"])){ $level2 = $jsonStruct[$j]["categorypath"]; for($m=0; $m<count($level2); $m++){ if(isset($level2[$m]["categoryName"])){ $catgName2 = $level2[$m]["categoryName"]; print_r("\nFound: $catgName2"); if($catgName2 == $exp[1]){ $notFound2 = false; $indexLevel2 = $m; if(isset($level2[$m]["categorypath"])){ $level3 = $level2[$m]["categorypath"]; for($n=0; $n<count($level3); $n++){ //print_r($level3["categoryName"]); if(isset($level3["categoryName"])){ $catgName3 = $level3["categoryName"]; print_r("\ncatgName3: ". $catgName3); if($catgName3 == $exp[2]){ $notFound3 = false; if($level3["products"]){ print_r("\npushing into array\n"); array_push($jsonStruct[$j]["categorypath"][$m]["categorypath"]["products"],array($itm)); }else{ print_r("\ncreate new and pushing into array\n"); $jsonStruct[$j]["categorypath"][$m]["categorypath"][$n]["products"] = array(); array_push($jsonStruct[$j]["categorypath"][$m]["categorypath"]["products"],array($itm)); } } } } } } } } } } } if($notFound1){ print_r("\nNotFound1\n"); array_push($jsonStruct, array("categoryName"=> $exp[0], "categorypath" => array("categoryName" => $exp[1],"products" => array($itm)))); }else if($notFound2){ print_r("\nNotFound2\n"); if(!$jsonStruct[$indexLevel1]["categorypath"]){ $jsonStruct[$indexLevel1]["categorypath"] = array(); } array_push($jsonStruct[$indexLevel1]["categorypath"], array("categoryName"=> $exp[1], "categorypath" => array("categoryName" => $exp[2], "products" => array($itm)))); }else if($notFound3){ print_r("\nNotFound3\n"); //$jsonStruct[$indexLevel1]["categorypath"][$indexLevel2]["categorypath"] = array("categoryName"=> $exp[2], "products" => array($itm)); if(!$jsonStruct[$indexLevel1]["categorypath"][$indexLevel2]["categorypath"]){ $jsonStruct[$indexLevel1]["categorypath"][$indexLevel2]["categorypath"] = array(); } array_push($jsonStruct[$indexLevel1]["categorypath"][$indexLevel2]["categorypath"], array("categoryName"=> $exp[2], "products" => array($itm))); } } } } jsonCreateStruct(); print_r("----------------------------------------"); print_r($jsonStruct); // echo json_encode($jsonStruct);
I have now reached a point where I desperately need help from experts.
Quote from: Hollows on August 20, 2010, 11:29:25 AM I have an array that is pulling 10 results from a db like this - <?php $result = mysql_query("SELECT * FROM inbox ORDER BY id DESC LIMIT 0,10"); while ($row = mysql_fetch_array($result)) { <div class="<?php echo $row['class']; ?>"> <?php echo $row['name']; echo $row['message']; ?> </div> basically 'class' is defined in an earlyier part of the script and is used to tell the css what class to display - as I'm sure you can see. What I'd like todo then be able to update the class of a message once I have read it, so update the class table with something like 'read' so the css will then be based on .read not what ever was set by the form, either using a link or form button inside each of the 10 results from the array. I've managed to update one by using - Code: [Select] mysql_query("UPDATE shoutbox SET class = 'read' WHERE id = ''XX"); // XX should be row id But I had to set that myself and point the id to the row id I wanted to change - How can I have that already populated with the row for the id that triggered it? To be clear so it looks like - Name Message read button _____________ Name Message read button _____________ Name Message read button _____________ and so on... Would I be better going by check boxes and one submit button? If so how could I implement that? I can provide the full code I've written if it helps Thank you in advance When I remove 1 session item using this it works fine when I select more than 1 item to be removed I get unexpected results, I have checked the outputted html to see what positions get echoed into the remove check box and they are correct, so I guess the problem lies in my remove code here is the part of the form that sends the remove check box <?php for ($basket_counter=0;$basket_counter<$_SESSION['ses_basket_items'];$basket_counter++) { $price=sprintf("%01.2f",$ses_basket_price[$basket_counter]); $quantity=$ses_basket_amount[$basket_counter]; $code=$ses_basket_stockcode[$basket_counter]; $itemID=$ses_basket_id[$basket_counter]; $name=$ses_basket_name[$basket_counter]; $image=$ses_basket_image[$basket_counter]; $size=$ses_basket_size[$basket_counter]; $sizechoice=$ses_basket_sizechoice[$basket_counter]; // create array from sizes and make the option box selections if ($sizechoice!="" && (!in_array($sizechoice, array('One Size', 'one size', 'free size', 'Free Size', 'Adjustable', 'adjustable')))) { // add size trigger $sizelist="add"; //create the array $sizepick=explode(",", $sizechoice); } else { $sizepick=$sizechoice; } // adjust gst for AU customers if ($country=='AU') { $price=sprintf("%01.2f",($price*1.1)); $unit=sprintf("%01.2f",($price/$quantity)); } else { $unit=sprintf("%01.2f",($price/$quantity)); } ?> <tr> <td align='center' class='rescon' style="border-bottom:solid #330000 1px;"><input type="checkbox" name="remove[<?php echo $basket_counter; ?>]" value="<?php echo $basket_counter; ?>" /></td> and here is the part of the code that processes the removal of the items $remove = $_POST['remove']; if (isset($remove) && ($remove!='')) { foreach($remove AS $key => $remove_position){ array_splice ($ses_basket_name, $remove_position, 1); array_splice ($ses_basket_amount, $remove_position, 1); array_splice ($ses_basket_price, $remove_position, 1); array_splice ($ses_basket_stockcode, $remove_position, 1); array_splice ($ses_basket_image, $remove_position, 1); array_splice ($ses_basket_size, $remove_position, 1); array_splice ($ses_basket_sizechoice, $remove_position, 1); array_splice ($ses_basket_id, $remove_position, 1); $_SESSION['ses_basket_items']--; } } I am using a form with checkboxes named remove[$remove_position] and the positions in the form are correct for each item in the array, but when I select more than 1 item to delete they are not always the correct items only the first 1 selected. What am I doing wrong here?? Sample array: array('one','two','three','_zero'); How could I sort this array so that _zero moves to the front.. Any items that begin with an underscore should be moved to the front of the array to get something like so: _zero, one, two, three Thanks So I'm querying my database to add the results (mapID's) into a PHP array. The MySQL query I used in the below code would usually return 10 values (only 10 mapID's in the database) Code: [Select] while($data = mysql_fetch_array(mysql_query("SELECT mapID FROM maps"))){ $sqlsearchdata[] = $data['mapID']; } Instead the page takes ages to load then gives this error: Quote Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 16 bytes) It says the error begins on the first line of the above code. I'm assuming this is not the right way to add the value from the MySQL array into a normal PHP array. Can anyone help me? I have users in my database with many stored points ie age, gender, interests etc. about 20 points in all.
I have a table of products that I want to recommend only applicable products. They each have saved like minage, maxage, gender, interest etc for the ideal consumer. ie dress gender=f
This is the bare bones of what I have so far:
$result = mysql_query("SELECT * FROM user_table WHERE hash='$session_id'"); $rowuser = mysql_fetch_array($result); $result = mysql_query("SELECT * FROM products"); $rowproducts = mysql_fetch_array($result);So now I have $rowuser['gender'] = m , how do I remove all from $rowproducts where gender = f? Is there a best way to do this knowing I have about 20 points to go through before I am left with an array with just the best selection of products for this user in it? Hey again, Still on the same project but now doing the cart page. I've been bringing my skills up to date a lot doing this project, however, having said that I now can't figure out why my cart is not adding the items to the cart, i've checked the post data and the quantity is set to 1. Would really appreciate someone having a look at it and hopefully can see what i'm missing. you can see what it should look like (well so far lol) at here in my sandbox site. thanks again. (p.s. The parts are all over the place on the page, so thought better put whole page, sorry if shouldn't have done that) <?php // Initialize the session session_start(); // Include config file require_once "dbcontroller.php"; $db_handle = new DBController(); if(!empty($_GET["action"])) { switch($_GET["action"]) { case "add": if(!empty($_POST["quantity"])) { $productByCode = $db_handle->runQuery("SELECT * FROM products WHERE product_code='" . $_GET["product_code"] . "'"); $itemArray = array($productByCode[0]["product_code"]=>array('product_name'=>$productByCode[0]["product_name"], 'product_code'=>$productByCode[0]["product_code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["img1"])); if(!empty($_SESSION["cart_item"])) { if(in_array($productByCode[0]["product_code"],array_keys($_SESSION["cart_item"]))) { foreach($_SESSION["cart_item"] as $k => $v) { if($productByCode[0]["product_code"] == $k) { if(empty($_SESSION["cart_item"][$k]["quantity"])) { $_SESSION["cart_item"][$k]["quantity"] = 0; } $_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"]; } } } else { $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray); } } else { $_SESSION["cart_item"] = $itemArray; } } break; case "remove": if(!empty($_SESSION["cart_item"])) { foreach($_SESSION["cart_item"] as $k => $v) { if($_GET["product_code"] == $k) unset($_SESSION["cart_item"][$k]); if(empty($_SESSION["cart_item"])) unset($_SESSION["cart_item"]); } } break; case "empty": unset($_SESSION["cart_item"]); break; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>LeaversHoodies.ie</title> <!-- Bootstrap --> <link href="css/bootstrap-4.4.1.css" rel="stylesheet"> <link href="css/accordian.css" rel="stylesheet"> </head> <body> <?php include 'header_student.php'; ?> <br /> <?php $school_page = "ravenswell"; $sql = "SELECT * FROM schools WHERE school_page = '$school_page'"; if($result = mysqli_query($conn, $sql)) while($row = mysqli_fetch_array($result)) { ?> <h3 class="text-center">Student Ordering Page For</h3> <h2 class="text-center" style="text-transform:uppercase;"><?php echo $row['school_name']; ?></h2> <hr style="width: 50%; text-align:center; border: 2px solid #00aeef; border-radius: 5px; margin: 0 auto;"> <br /> <div class="container"> <div class="row"> <div class="col"> <?php $path = "images/schools/"; $file = $row["logo"]; if(!empty($row['logo'])) { echo '<img src="'.$path.$file.'" style="width:95%; height:auto; margin-top:-130px;"><br /><br />'; } else { echo '<img src="images/schools/140x140.gif" style="width:95%; height:auto; margin-top:-130px;"><br /><br />'; } ?></div> <div class="col-6"> <h5>These are the garments your school has choosen :</h5><br /> <?php $school_id = $row["school_id"]; } var_dump($_SESSION); var_dump($_POST); $product_array = $db_handle->runQuery("SELECT * FROM choices INNER JOIN products USING (product_code) INNER JOIN colours USING (colour_id) WHERE school_id = '$school_id'"); if (!empty($product_array)) { foreach($product_array as $key=>$value){ ?> <div class="container"> <div class="row"> <div class="col-5" style="text-align:left;"> <img src="images/products/<?php echo $product_array[$key]["img1"]; ?>" alt="<?php echo $product_array[$key]["product_code"]; ?>" style="position:relative; top:0; width:200px; display:block;"> </div> <div class="col-7"> <h5><?php echo $product_array[$key]["product_name"]; ?></h5><p> in <?php echo $product_array[$key]["colour_name"]; ?></p> <p style="font-size:12px;"><?php echo $product_array[$key]["description"]; ?></p> <?php $comment = $product_array[$key]["comment"]; if (empty($comment)) { echo ""; } else { ?> <p style="font-size:12px;"><b>A note from your teacher:</b> <br /> <?php echo $product_array[$key]["comment"]; ?></p> <?php }; ?> <form action="student_order.php?schoolname=<?php echo $school_page; ?>?action=add&product_code=<?php echo $product_array[$key]["product_code"]; ?>" method="post"> <?php $product = $product_array[$key]["product_code"]; ?> Please select your size : <select id="size" name="size"> <?php $sql1 = "SELECT DISTINCT * FROM sizes WHERE product_code = '$product'"; if($result1 = mysqli_query($conn, $sql1)) while($row3 = mysqli_fetch_array($result1)){ echo "<option value='" . $row3['size'] . "'>" . $row3['size'] . "</option>"; } else { echo "nothing to see here"; } ?> </select> <br /><br /> <div class="number">How many do you want: <input type="number" style="font-size:12px;" id="quantity" name="quantity" value="1" min="1" max="5"><br /> Price : <?php echo "€".$product_array[$key]["price"]; ?> </div> <input type="hidden" id="product_code" value="<?php echo $product; ?>"><br /> <input type="submit" style="font-size:12px;" value="Add to Order" class="btnAddAction"> </form> </div> </div> <br /><hr style="width: 90%; text-align:center; border: 1px solid #00aeef; border-radius: 5px; margin: 0 auto;"><br /> </div> <?php } } else { echo "No Schools by that name registered."; } ?> </div> <div class="col-3"> <div style="border: 1px solid #d3d3d3; padding: 10px; border-radius: 5px; margin-top:30px;"> Your Order: </div> </div> </div> <div class="txt-heading">Shopping Cart</div> <a id="btnEmpty" href="student_order.php?schoolname=<?php echo $school_page; ?>?action=empty">Empty Cart</a> <?php if(isset($_SESSION["cart_item"])){ $total_quantity = 0; $total_price = 0; ?> <table class="tbl-cart" cellpadding="10" cellspacing="1"> <tbody> <tr> <th style="text-align:left;">Name</th> <th style="text-align:left;">Code</th> <th style="text-align:right;" width="5%">Quantity</th> <th style="text-align:right;" width="10%">Unit Price</th> <th style="text-align:right;" width="10%">Price</th> <th style="text-align:center;" width="5%">Remove</th> </tr> <?php foreach ($_SESSION["cart_item"] as $item){ $item_price = $item["quantity"]*$item["price"]; ?> <tr> <td><img src="images/products/<?php echo $item["img1"]; ?>" class="cart-item-image" /><?php echo $item["product_name"]; ?></td> <td><?php echo $item["product_code"]; ?></td> <td style="text-align:right;"><?php echo $item["quantity"]; ?></td> <td style="text-align:right;"><?php echo "$ ".$item["price"]; ?></td> <td style="text-align:right;"><?php echo "$ ". number_format($item_price,2); ?></td> <td style="text-align:center;"><a href="student_order.php?schoolname=<?php echo $school_page; ?>?action=remove&product_code=<?php echo $item["product_code"]; ?>" class="btnRemoveAction"><img src="icon-delete.png" alt="Remove Item" /></a></td> </tr> <?php $total_quantity += $item["quantity"]; $total_price += ($item["price"]*$item["quantity"]); } ?> <tr> <td colspan="2" align="right">Total:</td> <td align="right"><?php echo $total_quantity; ?></td> <td align="right" colspan="2"><strong><?php echo "$ ".number_format($total_price, 2); ?></strong></td> <td></td> </tr> </tbody> </table> <?php } else { ?> <div class="no-records">Your Cart is Empty</div> <?php } ?> </div> </div> <br /><br /> <?php include 'footer_student.php'; ?> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery-3.4.1.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/popper.min.js"></script> <script src="js/bootstrap-4.4.1.js"></script> </body> </html>
I have a webpage where all the database items are displyes in a table format.The table also has a check box.Upon clicking the delete button i need to delete all the items whish has the checkbox checked. How will i do that |