alphabetically sort array based on first few strings - php

I woud like to sort an array which typically includes names and email addresses. The problem is that the email addresses appear last even though they may start with 'a'
e.g.
$myarray = ("Alex Mayfeild", "David Beckham", "Oliver Twist", "ant.stev#wherever.com", "peter.pan#neverland.com", ........) //and so on
Upon sorting the array using php's sort function "ant.stev#wherever.com" will appear close to the end even though the functionality I would like to achieve is for him to appear after Alex.
natcasesort and natsource functions based on natural ordering seem to fail. Correction: natcasesource works it returns true when working as stated in docs. Thanks #meagar
Is there anyway to achieve the requested functionality. Thanks for any help guys. It is very much appreciated.

sort() is case sensitive, as it sorts based on the letters ASCII value.
Try natcasesort(), if you want too "sort an array using a case insensitive 'natural order' algorithm".

Seems to me that sort($myarray, SORT_STRING|SORT_FLAG_CASE); should sort the array the way you want.

Related

array_unique does not sort a simple string array

According to the PHP documentation, array_unique removes duplicate values and sorts the values treated as string at first.
When you take the following snippet in mind:
// define a simple array of strings, unordered
$brands = [ "BMW", "Audi", "BMW", "Chrysler", "Daewoo"];
// distinct the values, and sort them
echo array_unique($brands, SORT_STRING);
I would expect the output to be:
expected: {"0":"Audi","1":"BMW","3":"Chrysler","4":"Daewoo"}
actual : {"0":"BMW","1":"Audi","3":"Chrysler","4":"Daewoo"}
The question is: why doesn't array_unique sort these values? Changing the sort_flags parameter to any of the four alternatives, or leaving it empty, has no effect either.
According to other SO questions, like "Why does array unique sort the values" I'm probably missing something obvious here. Also, using array_values(array_unique($brands)), as stated as an answer in this question doesn't seem to work either.
Update: As stated in the useful comments and answers, the sort_flags parameter is actually an inner compare behavior, or equality operator, sort of speak.
In manual they mean that values group by value and first key taken for eacj duplicated value.
you need something like this
$brands = array_unique($brands);
sort($brands);
SORT_STRING - is default
The documentation simply specifies how the algorithm is working internally to achieve its purpose. Why and how is well explained in the other question. It does not say that the returned result will be sorted as well. Sorting is outside the scope of this function and probably actually undesired most of the time.
For completeness, this is how'd you unique (is that a verb?) and sort the array:
$array = array_unique($array);
sort($array);

PHP Sort Complex Array

Instead of working with mysql data, I have created csv file that I plan to use as the source of data for content, etc.
And I have successfully been able to parse the csv and store it into a complex array, that has the following header row aka the keys for the arrays.
"Title","Year","Rated","Released","Runtime","Genre","Director","Writer","Actors","Plot","Language","Country","Awards","Poster","Metascore","imdbRating","imdbVotes","imdbID","Type","Response"
My current stage is to allow dynamic ajax sorting of the arrays.
I have two fields, that I am allowing sorting at the beginning, "Year" and "Title".
So I pass different url paramters, such as "yearasc" or "yeardesc" or "titleasc" or "titledesc".
Then try to sort for that.
So what I did reading a different so post, was to do this.
First I create new arrays that only store the key fields, I need for sorting.
Then based on what sort type, do a different array_multisort.
array_multisort($year, SORT_ASC, $all_rows);
But what I get is results that multiple dupplicate data.
But I wonder if having the first row, be the header row, which is required by the function I pass the data after any sorting to, is causing issues with array sorting.
For simple array sorting, existing functions makes sense and work fine.
But for complicated ones, it is just complex to even understand how to approach solving this problem.
Any suggestions, thoughts or ideas are appreciated and thanked.
Thank you!
I don't have the actual code that is probably going to help you, but I do have a suggestion as for how you can tackle this and make it work..
Keep it simple. First, create your own CSV with just 1 header (Year or Title ) that you want to sort on.
Write your code to sort on that.
Then, add the other one ( Title if you used Year before, or Year if you used Title before ) and sort on whichever you want.
Then, add one more header (say, Rated) that you don't want to sort on.
You should then be able to work with the original CSV.
I'd try to write simple methods and keep your processing to a minimum in each one.
I hope that helps. I realize its more philosophical of an answer, so it is hit or miss if it helps you get the job done. Just realize that this approach will, indeed, take a little more time to write - but the point behind it is that you're taking out all of the "noise" that's getting in your way first. It helps you look at only your problem first and solve that.
You can set a custom sort function to the array. Use asort() if you need to keep original array keys.
<?php
$sortfields = array('year', 'bleh');
function cmp($a, $b) {
global $sortfields;
foreach ($sortfields as $sortfield) {
$cmp = strcmp($a[$sortfield], $b[$sortfield]);
// if desc, invert sign of $cmp
if ($cmp !== 0)
return $cmp;
}
return 0;
}
usort($all_rows, "cmp");
The function usort() calls a user defined comparison function, which returns the same logic from strcmp function: 0 if equal, < 0 is $a is less than $b and > 0 if $a is greater than $b.
This function will compare each field set in $sortfields variable, if it find any comparison that is different (in the order set), it will immediately return the difference.

scandir - sort numeric filenames

Done some searching, but can't seem to find the exact answer I'm looking for.
I'd like to pull in files with numbered filenames using 'scandir($dir)', but have them sort properly. For example, file names are:
1-something.ext
2-something-else.ext
3-a-third-name.ext
.
.
.
10-another-thing.ext
11-more-names.ext
The problem I'm having is that 10-a-fourth-thing.ext will show before 2-something-else.ext. I'd like to find a better way of solving this issue than introducing leading '0' in front of all file names.
Any thoughts? Thanks.
natsort does exactly what you need.
sort with SORT_NUMERIC will also work for filenames that start with numbers, but it will break if there are also names that have no numbers in front (all non-number-prefixed names will be sorted before number-prefixed names, and their order relative to one another will be random instead of alphabetic).
You can use sort like this:
sort($arr, SORT_NUMERIC); // asuming $arr is your array
If you want to reassign keys (which natsort does not do), use usort() combined with strnatcmp() or strnatcasecmp():
usort($arr, 'strnatcmp'); // Or 'strnatcasecmp' for case insensitive

Best way to replace strings

I have an array where I'm storing the bad and good string pairs.
Ex.:
array(
"Man. United"=>"Manchester United",
"Bay. Munchen"=>"Bayern Munchen",
"Bay. Munich"=>"Bayern Munchen",
...
)
so in this case I'm using strtr to replace the given string, but in this case I always have to add or remove data's from the array. Is there any way to store just the good names in one array and replace which is very similar? For me is much easier to build up the array with the good names.
You could use similar_text or one of the other functions mentioned in the see also section to try and correct them automatically, but won't be as accurate as if you list the spelling mistakes yourself.
*edit: levenshtein may also be a good one to try...
The Levenshtein distance is defined as the minimal number of
characters you have to replace, insert or delete to transform str1
into str2.

how to set array element/sort array in php

Hello All i want to sort the array in the way that
ASC order of user id
there is array like $user
i want to sort on the base
id $user['role'] =1;
then that element will set at the top of the array
Look in the PHP manual at asort, sort, and ksort. I'm not exactly sure what you're asking, but one of them is bound to do what you need.
Does that information come from a database? In that case, doing something like ORDER BY role DESC, user_id would be better than having PHP sort it for you.
If your array example $user['role'] = 1 means that 1 is the user id you want to use sort($user); however if role is going to be numeric you would want asort($user); instead as sort will overwrite numeric keys. As #Rob above said you may want to use ksort but only if you are making the array $user[user_id] = role.
Hope this helps
Regards
Luke
Thanx All For Replying on my question
i got the solution here it is
function compare($a,$b)
{
return strcmp($a["role"]['ID'], $b["role"]['ID']);
}
usort($a,compare);

Categories