PHP - Sort Array By Year Gives Wrong Order
Hi, I have a loop which creates an array: $productions[] = array( 'url'=>get_the_permalink(), 'year'=>$production_year->name, 'title'=>get_the_title() ); When I output the results, the year is in the wrong order:
2019 What I can't work out is how to order 2014 - 2020 I tried ksort(array, SORT_STRING) and ksort(array, SORT_NUMERIC) I also tried natsort But still have the same issue - am I missing something? Thanks Similar TutorialsHi 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 Hello, not sure if lack of sleep or just staring at code too long. This is what I have: Code: [Select] while($rowy = mysql_fetch_array( $resulty )) { mpdate = YYYY-MM-DD $date = $rowy['mpdate']; $year = explode('-', $date); $month = date("F", mktime(0, 0, 0, $year[1])); ?> <?php echo $year[0]; ?> <br> <?php echo $month; ?> <br> <?php echo $rowy['mptitle']; } ?> I figure if I use: if ($year[0] == date('Y"){ echo month and entry stuff } but I keep getting errors. What I am trying to do is sort everything out into year month and day ie: 2012 March Entry 1 Entry 2 February Entry 1 Entry 2 Entry 3 etc... This is what I am getting 2012 March Entry 1 2012 March Entry 2 2012 February Entry 1 etc... Is there a way to fix this? Hi guys, I have this SQL query which I use in my PHP search script Code: [Select] $query_for_result=mysql_query("SELECT * FROM customer WHERE c_name like '%".$query."%' OR c_telephone like '%".$query."%' OR c_address like '%".$query."%'"); It works fine, the only problem is now my database is bigger I would like to be able do SORT or ORDER BY id so that my search results are in order from asc to desc. Is this possible? if so can you help me. Thanks Hi guys, Having problems sorting mysql results. I can easily order/sort table columns but would like to order the results by a variable.(Distance in Miles). Havent much experience in PHP and really struggling with this. Basically a query echoing out car make and models and how far they are located from a postcode. Can get it to work no porblem, but not to order/sort by least distance. Heres what i'm working with: Code: [Select] $res=mysql_query("SELECT * FROM cars"); while ($row = mysql_fetch_assoc($res)){ echo $row['Make']; echo $row['Model']; //variable will be determimed by user input form $postcode="W12 3SR"; $start=$postcode; $ends = array(); //finds value from database field { $ends[]=$row['Location']; } // Postcode entered by user via input form $result=mysql_query("SELECT * FROM postcodes WHERE Pcode='$start'"); while($row=mysql_fetch_array($result)){ $gridn[0]=$row['Grid_N']; $gride[0]=$row['Grid_E']; } foreach($ends as $fin){ // Postcodes within mysql table $result=mysql_query("SELECT * FROM postcodes WHERE Pcode='$fin'"); while($row=mysql_fetch_array($result)){ $gridn[1]=$row['Grid_N']; $gride[1]=$row['Grid_E']; } // TAKE GRID REFS FROM EACH OTHER TO WORK OUT DISTANCE. $distance_n=$gridn[0]-$gridn[1]; $distance_e=$gride[0]-$gride[1]; // CALCULATE THE DISTANCE BETWEEN THE TWO POSTCODES AND DIVIDE BY 1.6 TO CONVERT KM TO MILES $hypot=sqrt(($distance_n*$distance_n)+($distance_e*$distance_e))/1.609; //VARIABLE FOR DISTANCE AND ROUNDED OF TO NEAREST WHOLE NUMBER. $distance=''.round($hypot/1000,0).''; echo " $distance miles"; echo "<br>"; } } ?> I wish i could just do something like this but isnt possible, is it ? Code: [Select] "Select * FROM cars ORDER BY $distance"; Thanks! For some reason every time I run this form it inserts an undefined value into the field called sortorder into my database table. The rest of the form inputs insert properly but that one. Here's the necessary coding. Anyone see why? form page <?php // Include the database page require ('../inc/dbconfig.php'); ?> <script type="text/javascript"> $(document).ready(function() { $('div.message-error').hide(); $('div.message-success').hide(); $("input.submit").click(function() { $('div.message-error').hide(); var charactername = $("input#charactername").val(); if (charactername == "") { $("div.message-error").show(); $("input#charactername").focus(); return false; } var charactershortname = $("input#charactershortname").val(); if (charactershortname == "") { $("div.message-error").show(); $("input#charactershortname").focus(); return false; } var sortorder = $("input#sortorder").val(); if (sortorder == "") { $("div.message-error").show(); $("input#sortorder").focus(); return false; } var style = $("select#style").val(); if (style == "") { $("div.message-error").show(); $("select#style").focus(); return false; } var status = $("select#status").val(); if (status == "") { $("div.message-error").show(); $("select#status").focus(); return false; } var alignment = $("select#alignment").val(); if (alignment == "") { $("div.message-error").show(); $("select#alignment").focus(); return false; } var division = $("select#division").val(); if (division == "") { $("div.message-error").show(); $("select#division").focus(); return false; } var dataString = 'charactername=' + charactername + '&charactershortname=' + charactershortname + '&sortorder=' + sortorder + '&style=' + style + '&status=' + status + '&alignment=' + alignment + '&division=' + division + '&submitcharacter=True'; $.ajax({ type: "POST", url: "processes/character.php", data: dataString, success: function() { $('div.message-error').hide(); $("div.message-success").html("<h6>Operation successful</h6><p>Character " + charactername + " saved successfully.</p>"); $("div.message-success").show().delay(10000).hide("slow"); $(':input','#characterform') .not(':submit') .val('') return true; } }); return false; }); }); </script> <!-- Form --> <form action="#" id="characterform" > <fieldset> <legend>Add New Character</legend> <div class="field required"> <label for="charactername">Character Name</label> <input type="text" class="text" name="charactername" id="charactername" title="Character Name"/> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="charactershortname">Character Short Name</label> <input type="text" class="text" name="charactershortname" id="charactershortname" title="Character Short Name"/> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="sortorder">Sort Order</label> <select class="dropdown" name="sortorder" id="sortorder" title="Sort Order"> <option value="0">- Select -</option> <?php $sortorder = 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","0-9"); foreach($sortorder as $so): ?> <option value="<?php echo $so; ?>"><?php echo $so; ?></option> <?php endforeach; ?> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="style">Character Style</label> <select class="dropdown" name="style" id="style" title="Style"> <option value="0">- Select -</option> <?php $query = 'SELECT id, stylename FROM styles LIMIT 2'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['stylename']."</option>\r"; } ?> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="status">Character Status</label> <select class="dropdown" name="status" id="status" title="Status"> <option value="0">- Select -</option> <?php $query = 'SELECT id, statusname FROM statuses'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['statusname']."</option>\r"; } ?> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="alignment">Alignment</label> <select class="dropdown" name="alignment" id="alignment" title="Alignment"> <option value="0">- Select -</option> <?php $query = 'SELECT id, alignmentname FROM alignments'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['alignmentname']."</option>\r"; } ?> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="division">Division</label> <select class="dropdown" name="division" id="division" title="Division"> <option value="0">- Select -</option> <?php $query = 'SELECT id, divisionname FROM divisions'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['divisionname']."</option>\r"; } ?> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <input type="submit" class="submit" name="submitcharacter" id="submitcharacter" title="Submit Character" value="Submit Character"/> </fieldset> </form> <!-- /Form --> <!-- Messages --> <div class="message message-error"> <h6>Required field missing</h6> <p>Please fill in all required fields. </p> </div> <div class="message message-success"> <h6>Operation succesful</h6> <p>Character was added to the database.</p> </div> <!-- /Messages --> validation page <?php // Include the database page require ('../inc/dbconfig.php'); if (isset($_POST['submitcharacter'])) { $charactername = mysqli_real_escape_string($dbc, $_POST['charactername']); $charactershortname = mysqli_real_escape_string($dbc, $_POST['charactershortname']); $sortorder = mysqli_real_escape_string($dbc, $_POST['sortorder']); $style = mysqli_real_escape_string($dbc, $_POST['style']); $status = mysqli_real_escape_string($dbc, $_POST['status']); $alignment = mysqli_real_escape_string($dbc, $_POST['alignment']); $division = mysqli_real_escape_string($dbc, $_POST['division']); $query = "INSERT INTO `characters` (charactername, charactershortname, status_id, style_id, division_id, alignment_id, sortorder, creator_id, datecreated) VALUES ('$charactername','$charactershortname','$status','$style','$division', '$alignment', '$sortorder', 1, NOW())"; mysqli_query($dbc, $query) ; } ?> Hey guys, I am having trouble figuring this out. I currently have a database that automatically sorts itself by the id of the data. But, I am wanting the user to be able to change the sort order via a select box. I already have the select box programmed with the options, but I am not sure how to go about coding the options to change the sort order of the displayed data. What would the best way to go about programming this be? Thank you very much ahead of time!! Hi i made a table which keeps player scores, but it is messed. Here's a link - http://kzlt.dev.lt/taure/rezultatai.php. How can i fix it ? The code: $text .= " <center><table border='1' width='565' height=30><tr><td width='15'>Nr.</td><td width='250'>&#381aid&#279jas</td><td width='150'><center>Ta&#353kai</center></td><td width='150'><center>Dalyvavo</center></td></tr>"; $result = mysql_query("SELECT * FROM taure_lentele ORDER BY score DESC"); while($row = mysql_fetch_array($result)) { if($rank == 1) { $color = "FF3300"; } else if($rank == 2) { $color = "FF6600"; } else if($rank == 3) { $color = "FF9900"; } else { $color = "FFCC00"; } $text .= '<tr bgcolor="'.$color.'"> <td width="15">'.$rank++.'</td> <td width="250"><b>'.$row['name'].'</b></td> <td width="150"><center>'.$row['score'].'</center></td> <td width="150"><center>'.$row['played'].' k.</center></td> </tr></center>'; } $text .= "</table>"; I have a php page that creates a photo gallery with thumbnails. It is populated by code that reads all photo files from a specified photo directory. This was working fine in DEV, but now that I have uploaded to my test web server, the pictures are in reverse order. Not the end of the world, yet annoying, because they should be in chronological order. Files names are straight off my iPhone (e.g. IMG_2203.jpg, IMG_2204.jpg, IMG_2207.jpg) What is happening, and how can I fix this? Thanks! Hello, i have two fields. a beginning year and an ending year. How can i make new fields out of the years in between the beginning and ending years. i hope that makes sense. 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 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) Hello all, I need to make a rotating banner system for a client. They want about 5 banners to rotate with Javascript. However they want the visitor to sort of step through each one on each refresh. So if I have 5 banners and I go to the site, I see banner 1 and then the javascript rotates through each one. When I go back to the site, they want it to start with banner 2 and then the javascript will rotate through each one. Then on and on. Go back and see banner 3, then step through again. I have a nice Javascript image slider I'd like to use. It basically just requires the images in order. Like: <img src="1.jpg"/> <img src="2.jpg"/> <img src="3.jpg"/> <img src="4.jpg"/> <img src="5.jpg"/> I've thought about it and I think the best way to do this would just be using PHP and a cookie. So when the viewer first goes to the site, PHP checks for the cookie. If it exists, it pulls the starting image #. If it doesn't, it starts at 0 and sets the cookie. As for the images part, I figured an associate array would work well. The key would be what the cookie logic is based on, and then the image HTML would be in the array. So you visit the site without a cookie it would be... 0 => <img src="1.jpg"/> 1 => <img src="2.jpg"/> 2 => <img src="3.jpg"/> 3 => <img src="4.jpg"/> 4 => <img src="5.jpg"/> Then when you go back to the site, I need the array to be re-ordered like this: 0 => <img src="2.jpg"/> 1 => <img src="3.jpg"/> 2 => <img src="4.jpg"/> 3 => <img src="5.jpg"/> 4 => <img src="1.jpg"/> What's the best way to go about this array logic? My experience with manipulating data inside arrays is rather limited. Basically I need it to say "Start with key # and then reorder array based on that" I have a bunch of PDF's, some of them having Uppercase first letters and some having lowercase first letters. Right now my code is alphabetizing all of the Uppercase first letters first then all of the lowercase. I want them to be mixed. $dir = "../../forms/pdf/"; foreach(glob($dir.'*.pdf') as $pdf){ $files[] = str_replace($dir, '', $pdf); } then: <select name="current_pdf" id="current_pdf"> <option value="">Please Select a PDF to replace</option> <?php foreach($files as $file) { echo "<option value=\"$file\">" . $file . "</option>"; } ?> </select> 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!! Hi, I have an array of type array_name[roll_number][aggregate_marks]. How do I sort such array on 'aggregate_marks'? My attempts on sort, asort haven't worked. Hello all, I have a rather large array and I need to list it's contents in an alphabetical list. The array is built like this: $array['query']['row']['0']['title'] = 'Bob'; $array['query']['row']['1']['title'] = 'Andy'; $array['query']['row']['2']['title'] = 'Tom'; I need to sort it so it is in alphabetical order based on the title. Is there an easy way to do this? 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 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 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'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. |