PHP - While Loop -> Array -> Sort -> Remove Duplicates
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... Similar TutorialsHi 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. Doing an API call and want to remove duplicates so I can display the products by brand. Problem I am having now is when I try to display the brands, I am getting duplicate brands. When I display the brands I am getting Nike, Nike, Reebook. When I just want, Nike, Reebok. My Code Code: [Select] <?php $results = array(); //array from API call $results2 = $results['data']; function multi_unique($array) { foreach ($array as $k=>$na) $new[$k] = serialize($na); $uniq = array_unique($new); foreach($uniq as $k=>$ser) $new1[$k] = unserialize($ser); return ($new1); } $results3 = multi_unique($results2); foreach ($results3 as $var) { echo $var['brand']; ?> <br /> <?php } ?> The array Code: [Select] { "errors": [ ], "warnings": [ ], "data": [ { "url": "http://[...]", "image_url": "[...]", "image_thumb_url": "[...]", "keyword": "Red Running Shoes", "description": "Red Running Shoes - Perfect for long jogs!", "category": "Shoes", "price": "59.99", "price_sale": null, "currency": "USD", "merchant": "", "brand": "Nike", "upc": "0944588778", "isbn": null, "sales": 23 }, { "url": "http://[...]", "image_url": "http://[...]", "image_thumb_url": null, "keyword": "Blue Running Shoes", "description": "Blue Running Shoes - Perfect for long jogs!", "category": "Shoes", "price": "59.99", "price_sale": "49.99", "currency": "USD", "merchant": "", "brand": "Nike", "upc": "0944588779", "isbn": null, "sales": 12 } { "url": "http://[...]", "image_url": "http://[...]", "image_thumb_url": null, "keyword": "Black Running Shoes", "description": "Black Running Shoes - Perfect for long jogs!", "category": "Shoes", "price": "59.99", "price_sale": "49.99", "currency": "USD", "merchant": "", "brand": "Reebok", "upc": "0944554779", "isbn": null, "sales": 12 } ], "coupons": [ ], "countryCode": "US", "page": 1, "limit": 10, "totalRecords": 3 } This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=349563.0 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); 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, got a problem with my arrays, every string gets duplicated 11 times instead of just one time. How to fix this? 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 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 wish to get only the last part of each array 'g' And then show non duplicated 'g' but in the same order that it was in the original array. Code: [Select] <?php $formarray = array( 'name' => array( 'i1'=> array('a'=>'a1', 'b'=>'b1', 'c'=>'c1', 'd'=>'d1', 'e'=>'e1', 'f'=>'f1', 'g'=>'g1'), 'i2'=> array('a'=>'a2', 'b'=>'b2', 'c'=>'c2', 'd'=>'d2', 'e'=>'e2', 'f'=>'f2', 'g'=>'g2'), 'i3'=> array('a'=>'a3', 'b'=>'b3', 'c'=>'c3', 'd'=>'d3', 'e'=>'e3', 'f'=>'f3', 'g'=>'g3'), 'i4'=> array('a'=>'a4', 'b'=>'b4', 'c'=>'c4', 'd'=>'d4', 'e'=>'e4', 'f'=>'f4', 'g'=>'g4'), ) ); foreach ($formarray as $newarray => $a) { ?><strong><?=$newarray;?></strong><br><? foreach ($a as $key => $k) { ?>"<?=$key;?>", <? foreach ($k as $b) { //if ($k['DBfield'] != "") { ?>"<?=$b;?>", <? //} } ?><br><? } //end of second foreach ?><br><br><br><? } //end of first foreach ?> $query = "SELECT painting, date1, date2, date3 FROM paintings WHERE artist_id = '$ar' "; $result = mysql_query ($query) or die ("Invalid query: " . mysql_error ()); while ($row = mysql_fetch_assoc ($result)) { echo "The 3 sale dates for ".$row['painting']." are"$row['date......." echo "<br>"; } Now within this while loop for each painting I want to echo out the 3 dates in order (sometimes date3 may be earlier than date1 or vice-versa). How do I sort those three dates when I am already in the while loop? Also how this work if one of the dates was blank? Thanks. Hi guys, I'm trying to sort an array. The array has information about listings. ID, name, info etc. An unrelated set of data also contains the listing ID's and I have made a function to sort this array and show an new order for the ID's. I now need to sort the original array by this new ID order... This snippet shows that the original listings array can be sorted by link_id: sort($this->links, $this->link->link_id); //This works. It sorts links by link ID! In a foeach loop I have created this: $sleeps_array[] = array("ID" => $link->link_id, "Sleeps" => $sleeps); // Makes an array of arrays of a custom field with listing ID. It makes this: array ( 0 => array ( 'ID' => '9', 'Sleeps' => '2', ), 1 => array ( 'ID' => '3', 'Sleeps' => '4', ), 2 => array ( 'ID' => '6', 'Sleeps' => '6', ), ) I can then sort this array of arrays with this function: function compare_sleeps($a, $b){ return strnatcmp($a['Sleeps'], $b['Sleeps']); } # sort alphabetically by name usort($sleeps_array, 'compare_sleeps'); It then gives me a sorted array according to "Sleeps" (as in, the number of people a property can cater for). It has the correct order of ID to then output but how do I organise the original array by ID with this new array? Sounds complicated, I hope you got that! Cheers, RJP1 Why does krsort return the array as "1"? Code: [Select] $m = array('34' => 1122, '6' => 1944, '9' => 1710); print_r($m); //outputs: Array ( [34] => 1122 [6] => 1944 [9] => 1710 ) print_r(krsort($m)); //outputs: 1 What i need is the output to be Array ( [6] => 1944 [9] => 1710 [34] => 1122) Is there a way to use sort($Array) on numbers but reverse it. So instead of 1 to 3 itll do 3 to 1 ? AKA descending order? Can't find a function that would do unless theres a second sort function ? Thanks I've got a multidimensional array that has 2 columns. The first column is numerical (country_id), and the second column is text (country_name), which may or may not be data that will be turned into an array. Looks something like this: column 1 (index 0) = 42 column 2 (index 1) = Great Britain|England I use a while loop to create an array of these rows, then a use a foreach loop to go through index[1] of each row. If there is a single name for a country, it is added to a new array, but if there is more than one name for a country, then both names are added to the new array. So, for example, if we had this data: row1 column 1 (index 0) = 12 column 2 (index 1) = Algeria row2 column 1 (index 0) = 22 column 2 (index 1) = Ethiopia row3 column 1 (index 0) =42 column 2 (index 1) = Great Britain|England Then the final array would look like this: index[0] = 12 index[1] = Algeria index[0] = 22 index[1] = Ethiopia index[0] = 42 index[1] = Great Britain index[0] = 42 index[1] = England Now I would like to sort by index[1] to get the following alphabetical order: index[0] = 12 index[1] = Algeria index[0] = 42 index[1] = England index[0] = 22 index[1] = Ethiopia index[0] = 42 index[1] = Great Britain What do I use? I've fooled around with sort, usort, asort ... can't figure it out. Thanks in advance. i need some help sorting my arrays. i have a class that selects data from database, and holds it inside a class to be used multiple times. rather then executing multiple queries. i know how to sort an array. but i am sorting arrays inside an array $data = arrray( array( 'id'=>1, '_name'=>'Server A', '_date_added'=>1298207645.5424, ); array( 'id'=>2, '_name'=>'Server B', '_date_added'=>1298247384.4839, ); array( 'id'=>3, '_name'=>'Server C', '_date_added'=>1298218493.0493, ); ); i want to sort my array descending by key _date_added hope you understand... Hi,
i have an issue to sort gallery photos by date. Right now its sort by Value (Name).
here is the code
index.php contains :
<div> <?php foreach($categories_array as $photo_category=>$photos_array){?> <?php $category_thumbnail = $gallery_url."/layout/pixel.gif"; if(file_exists('files/'.$photo_category.'/thumbnail.jpg')){ $category_thumbnail = $gallery_url.'/'.$photo_category.'/thumbnail.jpg'; } $category_url = $gallery_url.'/'.$photo_category; ?> <span class="category_thumbnail_span" style="width:<?php echo $settings_thumbnail_width;?>px; height:<?php echo $settings_thumbnail_height+20;?>px;"> <a class="category_thumbnail_image" href="<?php echo $category_url;?>" style="width:<?php echo $settings_thumbnail_width;?>px; height:<?php echo $settings_thumbnail_height;?>px; background-image:url('<?php echo $gallery_url;?>/layout/lens_48x48.png');" title="<?php echo htmlentities(ucwords(str_replace('-', ' ', $photo_category)));?>"> <img src="<?php echo $category_thumbnail;?>" width="<?php echo $settings_thumbnail_width;?>" height="<?php echo $settings_thumbnail_height;?>" alt="<?php echo htmlentities(ucwords(str_replace('-', ' ', $photo_category)));?>" /> </a> <a class="category_thumbnail_title" href="<?php echo $category_url;?>" title="<?php echo htmlentities(ucwords(str_replace('-', ' ', $photo_category)));?>"> <?php echo htmlentities(str_replace('-',' ', truncate_by_letters($photo_category, 16, '..')), ENT_QUOTES, "UTF-8");?> (<?php echo count($photos_array);?>) </a> </span> <?php } ?> </div>the sort function : ksort($categories_array); I've tried various sort methods on this array. And seem to be failing. Code: [Select] Array ( [monkey quest] => 8 [monkey] => 2 [monkey sports] => 0 [monkey go happy] => 0 [monkey go happy 3] => 1 [monkey joes] => 0 [monkey games] => 2 [monkey bread recipe] => 1 [monkey go happy 2] => 3 [monkey quest trailer] => 4 [monkey quest guide] => 5 [monkey quest nick] => 6 ) What I want to do or attempt to do rather is sort the array by the => value from highest to lowest (or maybe in reverse as well, but one thing at a time) My last failed attempt I was trying out usort() as my concept.. Code: [Select] function cmp($a, $b) { if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; } echo "<pre>"; print_r(usort($kw, "cmp")); echo "</pre>"; But the only thing I am left with on the page is just 1 everything else seems to be getting lost, or I dunno whats going on. So I think I've done stumped my self. Now I'm looking for idea's assuming I am tackling this all wrong. Hi freaks, Got a simple one for ya, I THINK? I have a multi-array that resembles this.. Code: [Select] $_SESSION["book_array"] = array(0 => array("plantID" => $plantID, "botanicalName" => $botanicalName, "commonName" => $commonName, "use" => $use)); I would like to sort it by the botanicalName key of the inner array before I call the forech loop that renders the display so that after it renders the table the items will be seen alphabetically, code below.. Code: [Select] <?php $bookOutput = ""; //$plant_use_array = ''; if (!isset($_SESSION["book_array"]) || count($_SESSION["book_array"]) < 1) { $bookOutput = '<tr><td colspan="4"><h6>Your Book is EMPTY!</h6></td></tr>'; } else { // Start the For Each loop $i = 0; foreach ($_SESSION["book_array"] as $each_item) { $plantID = $each_item['plantID']; $botanicalName = $each_item['botanicalName']; $botanicalName = stripslashes($botanicalName); $commonName = $each_item['commonName']; $commonName = stripslashes($commonName); $use = $each_item['use']; //$x = $i + 1; // Dynamic table row assembly $bookOutput .= "<tr>"; $bookOutput .= '<td><a href="plant_details.php?plantID=' . $plantID . '" id="bodyLink">' . $botanicalName . '</a></td>'; $bookOutput .= '<td>' . $commonName . '</td>'; $bookOutput .= '<td><strong>' . $use . '</strong></td>'; $bookOutput .= '<td><form action="book.php" method="post"><input name="removeBtn" type="submit" value="Remove"/><input name="index_to_remove" type="hidden" value="' . $i . '" /></form></td>'; $bookOutput .= '</tr>'; $i++; } } ?> Any help would be much appreciated! Thanks in advance. hi, i'm trying to sort an array of associative arrays, based on one of the keys. if the value of the key is a primitive, normal sorting occurs - this works fine. if the value of the key is an array, i'd like to have it sorted by "groups" here's an example: Code: [Select] <?php $data[] = array('name' => 'h', 'list' => array(1,2)); $data[] = array('name' => 'g', 'list' => array(1)); $data[] = array('name' => 'a', 'list' => array(1,3)); $data[] = array('name' => 'f', 'list' => array(2)); $data[] = array('name' => 'e', 'list' => array(2,3)); $data[] = array('name' => 'b', 'list' => array(3)); $data[] = array('name' => 'c', 'list' => array(1,2,3,4)); $data[] = array('name' => 'd', 'list' => array(3,4)); function deep_sort($array, $sorton){ usort($array, function($a, $b) use($sorton) { $a = $a[$sorton]; $b = $b[$sorton]; if(is_array($a) && is_array($b)){ // this bit is obviously flawed - only included for illustrative purposes $a = implode('', $a); $b = implode('', $b); } return ($a == $b) ? 0 : ($a > $b) ? 1 : -1; }); return $array; } $sorted_by_name = deep_sort($data, 'name'); print '<pre>'; print_r($sorted_by_name); print '</pre>'; $sorted_by_list = deep_sort($data, 'list'); print '<pre>'; print_r($sorted_by_list); print '</pre>'; ?> the sorted_by_name bit is fine - but for sorted_by_list, what i want returned is all the array ordered as follows: all those with "1" (or the lowest if none have "1") in it's list value first, then all those remaining that have the next highest ("2"), etc. so right now, the returns for sort_by_list look like this: Code: [Select] Array ( [0] => Array ( [name] => g [list] => Array ( [0] => 1 ) ) [1] => Array ( [name] => f [list] => Array ( [0] => 2 ) ) [2] => Array ( [name] => b [list] => Array ( [0] => 3 ) ) [3] => Array ( [name] => h [list] => Array ( [0] => 1 [1] => 2 ) ) [4] => Array ( [name] => a [list] => Array ( [0] => 1 [1] => 3 ) ) [5] => Array ( [name] => e [list] => Array ( [0] => 2 [1] => 3 ) ) [6] => Array ( [name] => d [list] => Array ( [0] => 3 [1] => 4 ) ) [7] => Array ( [name] => c [list] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) ) )whereas i'd like to get back: Code: [Select] Array ( [0] => Array ( [name] => g [list] => Array ( [0] => 1 ) ) [1] => Array ( [name] => h [list] => Array ( [0] => 1 [1] => 2 ) ) [2] => Array ( [name] => c [list] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) ) [3] => Array ( [name] => a [list] => Array ( [0] => 1 [1] => 3 ) ) [4] => Array ( [name] => f [list] => Array ( [0] => 2 ) ) [5] => Array ( [name] => e [list] => Array ( [0] => 2 [1] => 3 ) ) [6] => Array ( [name] => b [list] => Array ( [0] => 3 ) ) [7] => Array ( [name] => d [list] => Array ( [0] => 3 [1] => 4 ) ) ) TYIA for any suggestions Hello, Im struggling with this, probably because of my lack of fundamental knowledge of arrays. What i want to do is: make an array with two keys. 'id' and 'distance'. I want to sort the results by distance, displaying the id's... im looking at ksort() as the solution, however i don't think im implementing it properly as i dont think i have set the array up properly!! what i have is not good... Code: [Select] <?php while ($row = mysql_fetch_array($result)) { //get the photographers postcode and split it into 2 pieces $p_postcode = explode(' ',$row['address_post_code']); //get the photographers postcode and split it into 2 pieces $u_postcode_a = explode(' ',$u_postcode); //run the two postcodes throught the function to determin the deistance $final_distance = return_distance($u_postcode_a[0], $p_postcode[0]); //start the variable so we can add to it later on $photographers_inrange = ""; //declare this variable to help with the comma spacing too EDIT LOOK TO LINE 46 //$i2 = 1; $photographers_inrange = array(); //if the distance is smaller or equal to the distance the photographer covers if($final_distance <= $row['cover_distance']){ //get their id $photographers_inrange['id'] = $row['ID'].','; $photographers_inrange['distance'] = ''.$final_distance; //echo $photographers_inrange; //EDIT: this method does not work when just one result is returned. now i use substr -1. //if this isnt the last result //if($i++ <= $i2++){ //then add a comma for the sql statement //$photographers_inrange .= ','; //} } ksort($photographers_inrange); foreach ($photographers_inrange as $key => $val) { echo "togs[" . $key . "] = " . $val . "<br/>"; } ?> with $photographers_inrange being where it is, i am getting alot of empty arrays. not what i want. i just need to know how to add to the original array, and how to then sort it. thanks for your ongoing help!! |