PHP - Two Similar Items In An Array
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 Similar TutorialsHi, 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 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? 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. 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. 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?? 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.
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) 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 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? 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 im trying to run a query which will get posts from the database that have tags similar to the current ones. Unfortunatly the echoed result isnt displaying as it should. $query = $link->query("SELECT t.*, p.* FROM ".TBL_PREFIX."topics t JOIN ".TBL_PREFIX."posts p ON (p.p_tid = t.t_tid) WHERE t.t_name = '".decode_url($_GET['t_name'])."' LIMIT 1") or die(print_link_error()); $row = $query->fetch(PDO::FETCH_ASSOC); $tag_query = $link->query("SELECT p_name FROM ".TBL_PREFIX."posts WHERE MATCH (p_tags) AGAINST ('".$row['p_tags']."' IN BOOLEAN MODE) ")or die(print_link_error()); $result = $tag_query->fetch(); foreach($result as $key => $value) { echo 'Name = '.$result[$key]['p_name'].'<br />'; } i have done a dump of result and it shows: Code: [Select] $ => Array (2) ( ['p_name'] = String(12) "File Updates" ['0'] = String(12) "File Updates" ) but there should only be one item in this array(p_name). I dont know where the second is coming from. The query has pulled the right results, it just isnt displaying it right. Hello, I am looking for a push in the right direction. I would like to be able to view a website that is duplicated on many servers by specifying the IP address. Similar to how one would use the hosts file. I can do this using netcat nc 1.2.3.4 80 Host: example.com GET /contact-us.html <CR><CR> Can someone tell me how I would go about porting this to PHP? I would just like to set up a small page on my webserver where I can enter the domain and IP address and have the page displayed back to me. Thanks Colin hi My first language is not english so i hope you bear it i am new to php am am making my shopping Cart as my web engineering course i have made everything i all want to know how to i show similar products when a user click on any product details it open new page and shows a detail of that page i want to show similar products list below to details so can any tell me how to do it plzz kindly see the pic in atttachment i have posted snap shop of my page i put similar product statically i want to show it dynamically from tha data base kindly answer please regards I'm pretty sure there isn't, but I was wondering if there was a php function that would return partial matches similar to MySQL's LIKE, I've been searching for a while and haven't found one. If not, is there a class or something that someone knows of that will accomplish a like of search or a string comparison? I want to be able to compare two variables and return one of three results - Exact Match, Partial Match, No Match. I suppose regex may do the trick but I'm a complete novice when it comes to regex and I have no idea where to even begin. Thanks for any suggestions. How to COUNT the number of records (pulled from a db)which contains the word "APPROVED". This code doesn't work though. $result1; $result2; $result3; $approvedApplicants = COUNT($result1=='Approved', $result2=='Approved', $result3=='Approved') echo ($approvedApplicants) Hello, I need to be able to find what is inbetween 2 values in a string of text. For example, <?php $string="Hello and welcome to the site. Click [link]welcome.php[/link] here to continue to the site"; ?> So I need some method of searching the string to see what values are in between the [link] and [/link] which I will then deal with in my own way. I have a feeling that I could do this with explode, but I'm not really sure. Any advice? Thanks in advance |