PHP - How To Group Duplicates?
I have a table that has pairs of matching records that are identified as matching on a specific column. In other words, 2 users submit data on the same record, and they are identified as matching and belonging to the same record data because the table column gameid is the same for the pair.
How can I output the information for the pair of matching records for each of these into a table repeating it until Ive looped through all records? In other words I want to create 1 table with headers for each matching pair all the way down... thanks in advance. Similar TutorialsHi All, I've a loop which creates an array as follows: $product_table[] = ['SKU' => $sku, 'Label' => $attribute_name, 'Value' => $term_obj->name ]; I'm then grouping the data by SKU code: #group the products by SKU $group_products = array(); foreach ($product_table as $element) : $group_products[$element['SKU']][] = $element; endforeach; Finally, I output the data: #output the data foreach ($group_products as $itemName => $rows) : echo '<tr>'; #echo '<td>', $element['SKU'], '</td>'; $i=0; foreach ($rows as $row) : $i++; #echo '<td>'. $row["SKU"]. '</td><td>'. $row["Label"]. '</td><td>'. $row["Value"]. '</td>'; if ($i == 1): echo '<td>'. $row["SKU"]. '</td><td>'. $row["Value"]. '</td>'; else: echo '<td>'. $row["Value"]. '</td>'; endif; #echo '<td>'. $row["Value"]. '</td>'; endforeach; echo '</tr>'; endforeach; ?> And looks like: Product code System Pack Quantity XT1CWH System 1 1 x 3m XT2CWH System 2 1 x 3m XT3CWH System 3 1 x 3m
This works perfectly fine. However, some products share the same SKU and therefore it causes an issue, like the below: Product code System Pack Quantity XT1CLWH System 1 8 x 3m System 2 8 x 3m System 3 8 x 3m Is there a way I can avoid this, so if perhaps creates the new row but shows the same SKU code? Many thanks I need a way to keep entrys into a database from being doubled. The issue is that on something like %7B%7D that is the same as {} in html. So if one is entered in with the percentages and one is entered in normal, the data base thinks they are two different items even though they could be the exact same thing. Now when I insert the new item into the data base the value ='s mysql_real_escape_string(htmlentities(item)) is how I do it now. This is wrong im guessing cause it could go with either of the above examples and puts them in as given. So my question here is kinda two parted. 1) how do I get it to insert the info one way or the other but never both being allowed. So {} will always show %7B%7D when inserted or visa versa. and 2) How do I take an existing database and sort threw it to make sure they are all the same as 1 codes the new ones in, and take out any possible dupilications due to the difference? Hi, I have a database table which is full of books e.g book_title, book_author, book_date etc. Im trying to work out a way to list all the authors without duplicating them, if that makes sense. If I do a simple query and then display the book_author in a loop it will show multiple entries for each author. I just want it to display each author once. Hope that makes sense lol sorry Im a newbie. Anyone know how I can do it ? Thanks in advance, Scott. I've made a small chicken names website, and I also have a chicken name list as a thread on a chicken related forum. People submit their names, and I manually add them to the list. With the names growing so much, I decided to make a small background system that lets me put in the current list names, then the new names submitted. It will then run the lists, compare them, and spit out/ignore any duplicates and generate the new list. But each time I use it, it doesn't get rid of the duplicates. Can anyone tell me why? if($_GET['list_updater'] || $_POST['list_updater']) { if(!$_POST['current_list'] || !$_POST['new_names']) { ?> <table> <form action="index.php" method="POST"> <input type="hidden" name="list_updater" value="1"> <tr> <td> <textarea name="current_list" cols="40" rows="20"></textarea> </td> </tr> <tr> <td> <textarea name="new_names" cols="40" rows="20"></textarea> </td> </tr> <tr> <td><input type="submit" value="Generate New List"></td> </tr> </form> </table> <?php } else { //start our counting numbers $x = 0; $s = 0; $a = 0; //make our arrays $check_to[0]; $new[0]; //get the values from our lists $old_list = explode("\n",$_POST['current_list']); $new_list = explode("\n",$_POST['new_names']); //get new list variables foreach($old_list as $value) { $check_to[$x] = $value; $x++; } //add all our new names foreach($new_list as $value) { for($s = 0; $s < count($new_list); $s++) { } } ?> <textarea cols="45" rows="20"> <?php for($t = 0; $t < count($new); $t++) { echo $new[$t]; } ?> </textarea> <?php } } I'm figuring out a code that runs through several checkboxes, then checks the mysql table to enter any checked boxes if they don't already exist, and to delete any entries that might exist matching the unchecked boxes. This is as far as I've gotten. I had it working, but it chokes on the table key. I want to skip over existing entries... Code: [Select] if (isset($_POST['submit'])){ require ('db.php'); $id1 = $_POST['plant_id']; $imploder=implode(',', $_POST['option2']); $exploder = explode(',', $imploder); foreach($exploder as $value) { $add = "INSERT INTO table(plant_id, edible_id) VALUES ($id1, $value) WHERE plant_id = $id AND edible_id != $value"; $delete = "DELETE FROM table WHERE plant_id = $id1 and edible_id NOT IN $exploder"; }; $result2 = mysql_query($add) or die(mysql_error()); if (mysql_affected_rows() > 0) { echo '<div style="position:relative; left:16px; top:216px;"><font color="red">updated!</font></div>'; } } ?> Hello im trying to write a simple script so that before my website inserts an account into the database it checks to see if that email already exists. Heres what i got but it does not work. //script for checking if the email account already exists $CheckEmail = "SELECT * FROM Members WHERE email='".$email."'"; $EmailQuery = mysql_query($CheckEmail); $Emailresult = mysql_fetch_array($EmailQuery); $GotEmail = mysql_num_rows($EmailResult); if($GotEmail != 0) { $emailDup= "This email account has already been registered"; } else { //run the rest of my scripts later down the page I have this to echo the message <? if($GotEmail)==1 echo $emailDup; ?> I have a switch, which i use to alternate between two numbers. But for some reason, a duplicate occurs exactly at the count of 4, and i haven't been able to figure out why. Code: [Select] $Count = 1; switch ($Count) { case 1: ++$Count; break; case 2: --$Count; break; } Should output: Code: [Select] 2 1 2 1 2 ...But for some reason it gives the below instead.. Code: [Select] 2 1 2 1 1 2 1 ... Subsequent output after the error appears completely normal. Quote Hi guys im trying to get rid of records with duplicate phone numbers here's my array Code: [Select] Array ( [0] => Array ( [0] => 11-1-89677-362123164 [1] => 11 [2] => testadmin [3] => 61415676836 [4] => 2011-11-16 [5] => 1 [6] => 0 [7] => 0 [8] => [9] => 0 [10] => 0 [11] => 0 ) [1] => Array ( [0] => 11-1-89688-362186603 [1] => 11 [2] => testadmin [3] => 61415556677 [4] => 2011-08-12 [5] => 0 [6] => 0 [7] => 0 [8] => [9] => 0 [10] => 0 [11] => 0 ) [2] => Array ( [0] => 11-1-89689-362186773 [1] => 11 [2] => testadmin [3] => 61415676836 [4] => 2011-08-12 [5] => 0 [6] => 0 [7] => 0 [8] => [9] => 0 [10] => 0 [11] => 0 ) [3] => Array ( [0] => 11-1-89690-362186926 [1] => 11 [2] => testadmin [3] => 61415223344 [4] => 2011-08-12 [5] => 0 [6] => 0 [7] => 0 [8] => [9] => 0 [10] => 0 [11] => 0 ) ) Quote I can't quit figure this out any sujestions would be gold,,, this is my attempt but its not working Code: [Select] $final = array(); foreach ($phoneNumberArray as $array[3]) { if(!in_array($array, $final)){ $final[] = $array; } } print_r($final); Hey guys! I haven't really coded teh exact query for this yet. But what I want to do is I want to grab multiple results that are the same and only display one BUT also grab DIFFERENT results from the SAME table the same way. Let me give an example here... Lets say this is my table: id - name - image 1 - apple - apple.gif 2 - grape - grape.gif 3 - orange - orange.gif 4 - apple - apple.gif 5 - apple - apple.gif 6 - orange - orange.gif I want it to diaply like this: Apple -apple.gif- Quantity: 3 Orange -orange.gif- Quantity: 2 Grape -grape.gif- Quantity: 1 My query for LIMIT 1 would look like this, but it only grabs one result toal.. i think.. I would also be grabbing stuff from two different tables, which wouldn't be an issue. in this case, i want to grab the QUANTITY form one table, )the uitems table) and the image and name from the items table) the uitems query is also grabbing theitemid to use with the items table.. Code: [Select] \\ this would be getting the quantity \\ $query = "SELECT * FROM uitems WHERE username='$showusername' AND location='2'"; $thisthat = mysql_query($query); while($row = mysql_fetch_array($thisthat)) { $quantity = $row['quantity']; $getid = $ow['theitemid']; } \\ now getting the item info \\ $itemquery = "SELECT * FROM items WHERE itemid='$getid'"; $item = mysql_query($itemquery); while($thisrow = mysql_fetch_array($item)) { $name = $thisrow['name']; $image = $thisrow['image']; $actualid = $thisrow['itemid']; } So basically, I want to be able to be able to grab one row of every kind that is there. How can I do that? Thanks so much in advance!! =D There is no great way for me eliminate duplicates upon entry. I can't just use first name and last name, because sometimes we have kids with the same name. I can't really use their school because sometimes the parents just use the school name, other times they put HS after it or High School, etc.
So from year to year I get a lot of duplicate entries into my database. The problem arises for me when a kid is registered but doesn't pay right away, so mom or dad return to the site to pay, and instead of just paying they re-register. I'm trying to eliminate those.
Of course when that is the case, they generate a new ID so I started the
select * from fallLeague10 as f1 join fallLeague10 as f2 where f1.nameFirst = f2.nameFirst and f1.nameLast = f2.nameLast and f1.confirm='1' and f1.id <> f2.id order by f1.nameLast, f1.nameFirst(confirm = they entered this year) I really can't make sense of why it's producing the list that it is. I'm not really getting duplicates, maybe a couple, but there are definitely non-duplicates in that list. Basically, what I'm looking to get is 8-12 names that show up twice (or three times in one instance). It's a 470 person lot, and I just want to make sure I don't miss any because my numbers have to be exact or some kid ends up on two teams. I figure a query would be better than scrolling through my list. I've been working on this too long, without having it figured out. Starting to get a bit 'kooky' at this point! I'm one stage away from retarded frustration. I have two arrays, such as these: Array 1 ( => 7|1|0|5|0|0 [1] => 7|3|0|5|0|0 [3] => 7|4|0|5|0|0 [4] => 7|5|0|5|0|0 [5] => 7|6|0|5|0|0 [6] => 7|7|0|5|0|0 ) Array 2 ( => 8|1|0|5|0|0 [1] => 7|2|0|5|0|0 [2] => 7|3|0|5|0|0 [3] => 7|4|0|5|0|0 ) I am trying to write a piece of code that will compare every value in array 2 to every value in array 1 and if the first 2 NUMERICAL values do not exist in Array 1, they are to be added to it. So, in the end, after comparison, Array 1 should look like this: Array 1 ( => 7|1|0|5|0|0 [1] => 7|3|0|5|0|0 [3] => 7|4|0|5|0|0 [4] => 7|5|0|5|0|0 [5] => 7|6|0|5|0|0 [6] => 7|7|0|5|0|0 => [7] => 8|1|0|5|0|0 [8] => 7|2|0|5|0|0) The values 7|3|0|5|0|0 and 7|4|0|5|0|0 from Array 2 have not been added to Array 1 because 7|3... and 7|4... already exist in Array 1. So far, I've got something like this: Code: [Select] $match = 0; foreach ($array1 as $data1) { foreach ($array2 as $data2) { if ($data1 == $data2) { $match = 1; break; } } if ($match != 1) { array_push($array1, $data2); } else {$match = 0;} } Where have I gone wrong? Hi I have an array from an sql query and i would like to eliminates all the duplicates, i have google search for an answer without success, any help would be aprecciated $result = $stmt->fetchAll(PDO::FETCH_ASSOC); $final = array(); $json = array(); if ($idCoord > 0 || $isDirecao > 0) { foreach ($result as $row) { $idAtividade = $row['idAtividade']; if (!isset($final[$idAtividade])) { $final[$idAtividade]['Escola'] = $row['Escola']; $final[$idAtividade]['Atividade'] = $row['Atividade']; $final[$idAtividade]['Periodo'] = $row['Periodo']; $final[$idAtividade]['Mes'] = $row['Mes']; $final[$idAtividade]['haveClasses'] = $row['haveClasses']; $final[$idAtividade]['DataPrevista'] = $row['DataPrevista']; $final[$idAtividade]['Destinatarios'] = $row['Destinatarios']; $final[$idAtividade]['Orcamento'] = $row['Orcamento']; $final[$idAtividade]['Organizador'] = $row['Organizador']; $final[$idAtividade]['Obs'] = $row['Obs']; $final[$idAtividade]['PdfAtividade'] = $row['PdfAtividade']; $final[$idAtividade]['Avaliacao'] = $row['Avaliacao']; $final[$idAtividade]['idProfessor'] = $row['idProfessor']; $final[$idAtividade]['PdfAvaliacao'] = $row['PdfAvaliacao']; $final[$idAtividade]['Validado'] = $row['Validado']; $final[$idAtividade]['Nome'] = array(); $final[$idAtividade]['Grupo'] = array(); $final[$idAtividade]['Departamento'] = array(); } $final[$idAtividade]['Nome'][] = $row['Nome']; $final[$idAtividade]['Grupo'][] = $row['Grupo']; $final[$idAtividade]['Departamento'][] = $row['Departamento']; } foreach ($final as $idVisita => $reservation) { $json[] = $reservation; } } echo json_encode($json); } And this is an example i'm receiving
So you can see that Grupo has 4 times the value "500" and Departamento has 4 times that string... How can avoid this and have only one value of each?
Thanks
Hi guys! i got this code: Code: [Select] <? $x = "abcde"; str_split($x); for ($k=0; $k<=119; $k++){ $ax = array($x[0],$x[1],$x[2],$x[3],$x[4]); shuffle($ax); $text = implode("", $ax) . ""; echo $text; echo "<br />"; } ?> if you test it you see that it is working but giving me allot of duplicates results! there is a way to ignore duplicaes while it is runing? thanx. Hi,
I have a section of code that sends an order confirmation to me when a customer places an order with us.
This all works fine but recently, I have started to get duplicate confirmations coming from the same customers, one in particular, many times a day...
Is there anything obvious about this code that could be causing it?
Thanks,
<?php Hi. Please help me. I need an example of codes maybe 4-6 lines: example for code for small program that sorts the following string, eliminating duplicates. The string is: a, b, rt, tril, drv, b, span, drv, art, arc, d, a, drc Thank you Hello
I am working on a 3 field variable that is given in an array with A-Z and 1-26 and 26 words in total, being randomized and insert in database via mysql but it must checks to be sure there is no duplicate of any values at all.
here is my code, I managed to make the first value to work but the 2nd and 3rd doesnt.
<? // connection data mysql_connect("localhost", "user", "pass") or die("error ".mysql_error()); mysql_select_db("dbname") or die("error ".mysql_error()); function GenerateNumber(){ // selects random number $randomNumber = rand(1,26); return $randomNumber; } function GenerateLetter(){ // selects random position number in letters array to select an alphabet $LetterPosition = rand(0,25); $alphabet = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'); $randomLetter = $alphabet[$LetterPosition]; return $randomLetter; } function GenerateWord(){ // selects random word from an array -same method as letter $wordPosition = rand(0,25); $words = array('ah','book','cup','dice','elephant','flute','gum','house','idol','jumpingjacks','kite','lunchbox','matress','novel','olive','pumpkin','queen','rooster','stove','teacup','unicorn','violin','walurus','xerox','zebra'); $randomWord = $words[$wordPosition]; return $randomWord; } for($x=0; $x<=25;){ //generate letter,number,and word $randomLetter = GenerateLetter(); $randomNumber = GenerateNumber(); $randomWord = GenerateWord(); echo '<b>Generated Variables:</b>[ '. $randomLetter.' ][ '.$randomNumber.' ][ '.$randomWord.' ]<br />'; // there is data in the table, check if there is letter already assigned $first = mysql_query("SELECT * FROM test WHERE a_char='$randomLetter'"); if(mysql_num_rows($first) == 0){ //no letter is found, check if there is number already assigned $second = mysql_query("SELECT * FROM test WHERE aint='$randonNumber'"); if(mysql_num_rows($second) == 0){ //no number is found, check if there is word already assigned $thrid = mysql_query("SELECT * FROM test WHERE aword='$randomWord'"); if(mysql_num_rows($third) == 0){ //there is no letter,number, and word found in db, great! go ahead and insert! $fq = "INSERT INTO test (a_char,aint,aword) VALUES ('$randomLetter','$randomNumber','$randomWord')"; $final = mysql_query($fq); //increment the loop $x++; echo('[ '. $randomLetter.' ][ '.$randomNumber.' ][ '.$randomWord.' ] has been added in row '.$x.'<br /><br />'); }else{ echo("Repeated Word: ".$randomWord." generating another: "); //there is word already assigned, select another! $randomWord = GenerateWord(); echo($randomWord.'<br /><br />'); } }else{ echo("Repeated Number: ".$randomNumber." generating another: "); //there is number already assigned, select another! $randomNumber = GenerateNumber(); echo($randomNumber.'<br /><br />'); } }else{ echo("Repeated Letter: ".$randomLetter." generating another: "); //there is letter already assigned, select another! $randomLetter = GenerateLetter(); echo($randomLetter.'<br /><br />'); } } mysql_close(); ?> So Im building this little link scraper. The problem I am having is when it outputs the links that are in the array its got duplicate elements. I'm trying to erase the dupes and only show unique values. I've tryed array_unique() with out success as well as in_array(). Any help would be appreciated! //PAGE WE ARE GETTING LINKS ON $diags = str_get_html(getDiagramLinks($html)); //GET THE DIAGRAM LINKS TO PAGES INTO ARRAY foreach($diags->find('a') as $f) { $diagLinks[] = $f->href; } //iterate through the array for($i=0; $i<sizeof($diagLinks); $i++) { //ignore if blank element if(trim($diagLinks[$i]) !== ' ') { echo $diagLinks[$i]. '<br>'; } } The Output: Code: [Select] /partsearch/model.aspx?diagram_id=110375 /partsearch/model.aspx?diagram_id=110375 /partsearch/model.aspx?diagram_id=110376 /partsearch/model.aspx?diagram_id=110376 /partsearch/model.aspx?diagram_id=110377 /partsearch/model.aspx?diagram_id=110377 /partsearch/model.aspx?diagram_id=110378 /partsearch/model.aspx?diagram_id=110378 /partsearch/model.aspx?diagram_id=110379 /partsearch/model.aspx?diagram_id=110379 /partsearch/model.aspx?diagram_id=110380 /partsearch/model.aspx?diagram_id=110380 Hi, got a problem with my arrays, every string gets duplicated 11 times instead of just one time. How to fix this? while ( $categories = $category_result -> fetch_assoc() ) { $menu_sql = "select * from menu where category_id = {$categories['category_id']}"; $menu_result = $handle -> query( $menu_sql ); $category2 = strtoupper($categories['category']); echo '<h3 id="' . $category2 . '">' . $category2 . '</h3>'; while ($menu = $menu_result -> fetch_assoc()) { echo $menu['item_name'] . ' '; $size_sql = "select distinct size from size where category_id = {$categories['category_id']} order by size desc"; $size_result = $handle -> query( $size_sql ); while ($size = $size_result -> fetch_row()) { echo $size[0] . ' '; } //get base type from base_type table for the pizza category $type_sql = "select type from base_type where category_id = {$categories['category_id']}"; $type_result = $handle -> query( $type_sql ); while ($type = $type_result -> fetch_row()) { echo $type[0] . ' '; } //get price for each item from menu if it is not null $price_sql = "select price from menu where item_name = '{$menu['item_name']}'"; $price_result = $handle -> query( $price_sql ); while ($price = $price_result -> fetch_row()) { echo $price[0] . ' '; if( is_null( $price[0] ) ) { //get price from size table if price is null in menu table; //$categories = $category_result -> data_seek(0); $size = "double"; $category_id = $categories['category_id']; $item_id = $menu['item_id']; $type = 'deep'; echo $menu['item_id']; $price_size_sql = "select price from size where size = '$size' and category_id = $category_id and item_id = $item_id"; $price_size_result = $handle -> query( $price_size_sql ); while ($price_size = $price_size_result -> fetch_assoc()) { echo " {$price_size['price']} "; } } } echo '<br />'; } echo '<br />'; } I get duplicate vakues for $category_id = $categories['category_id']; $item_id = $menu['item_id']; dont know whats wrong it works for pizzas but not burgers, please help me. Hello I have a while loop which outputs countrys from the database (im making a "filter by" function). For example, the loop outputs: Denmark Belgium Holland Brazil Japan Brazil Denmark I want to sort these alphabetically and then remove duplicates... Can somebody explain to me how? I don't know how to get them into an array to do it... |