Is there any way to "custom" sort an array? For instance, if I have the following numbers:
$array = array('0' => 1, '1' => 2, '2' => 3);
I would like it to order them in this fashion:
$array = array('0' => 2, '1' => 1, '2' => 3);
How would I do this or is it not possible? I am basically wanting to list this array in one database field for each user, but each order will be different depending on how the user sorts the array.
Thanks, Jake
You can use
usort — Sort an array by values using a user-defined comparison function or
uksort — Sort an array by keys using a user-defined comparison function or
uasort — Sort an array with a user-defined comparison function and maintain index association
Each of these accepts an array and a user-defined comparison function aka callback. What you put into the comparion function is up to you. As of PHP5.3 you can also use SplHeaps to create ordered collections.
you may also want to have a look at array_multisort()
It might be better to let the database sort the array upon retrieval with the users settings. I think that is almost always preferable over sorting in PHP.
edit:
I forgot that the array is probably stored as a single object so the database just handles it as an object and not an array. To still enable serverside (database server) sorting, arrays could also be expressed as seperate tables:
userID : index0
userID : index1
etc...
but this might give too much data overhead.
Related
Say, we make an array like this:
$arr = Array
(
2 => 'c',
1 => 'b',
0 => 'a'
);
When you pass it to array_pop():
array_pop($arr);
And the "last" element would be poped off, which has the index of zero!!
print_r($arr);
Result:
Array
(
[2] => c
[1] => b
)
So, what's the purpose of index?
Isn't it just a different way of saying "numeric keys of associative arrays"?
Is it only PHP dose so, or all the languages treat arrays like this?
Not all languages do this, but PHP does, because PHP is a little weird. It implements arrays more or less like dictionaries. PHP does offer some functions like ksort though, which let you sort the array by key.
And that's what this is: a key. An array has indexes as well, so what you got, is an array where item 2 has key 0. And that's where the confusion starts continues.
PHP: a fractal of bad design has a whole chapter about arrays. Interesting reading material. :)
The reason for this behavior is because arrays in PHP are actually unordered maps.
Because of this, don't think of accessing the arrays in terms of indexes, think of it in terms of keys. Keys can be numbers and they can be strings, but the result is the same; you're still using a map, not a true "array".
Once you accept that fact, you'll understand why PHP includes functions like ksort() for sorting an array by keys and why array_pop() doesn't always remove the highest key value.
It's a PHP thing. Other languages usually provide other structures to provide what is the default behaviour for arrays on PHP. JavaScript for instance will always sort the array:
a = [];
> []
a[1] = 'a';
> "a"
a[2] = 'b';
> "b"
a[0] = 'c';
> "c"
a
> ["c", "a", "b"]
In Java you would need to use a Hash Map or something else to do Associative Arrays. PHP handles data structures more loosely than other languages.
The index allows you to identify and access the elements of the array.
the reason is simple HashTables.
in php internal functions often use HashTables. basically an array is some data in memory and like in C - an array index can only hold integer values but not in php.
php solves this with hashtables. if you asign a index example foo this value is not directly assigned as foo it gets hashed and maybe end internal as 000000000111 and other hash functions.
so php doesn't work directly with your assigned value and this is the reason why you can set an array index like 0 as last index element. internal php work with hashtables that have a "list" with values which index value is assigned to which position in the array.
I have an array of unique colors which is selected from a table. But keys of that particular array is not in sequence order due to some calculations. Now I wish to assign a sequence numbers to that array... Is any function to change keys of array..
Thanks...
Array(
[81]=>yellow
[86]=>gray
[93]=>wine
[103]=>marigold
[125]=>maroon
[134]=>pewter
[142]=>forestgreen
[151]=>grey
)
i wish to change this array to
Array(
[1]=>yellow
[2]=>gray
[3]=>wine
[4]=>marigold
[5]=>maroon
[6]=>pewter
[7]=>forestgreen
[8]=>grey)
If you want to sort your array by some calculation, you can use usort(), which sorts an array by using a callback function. In this callback function, you can compare two elements of the array and decide (by any means you need) which one goes first. Read through the examples on the page I linked to learn more!
use: sort($color); check the examples from this link: sort
I have this array
$myArray=array(
'a'=>array('id'=>1,'text'=>'blabla1'),
'b'=>array('id'=>2,'text'=>'blabla2'),
'c'=>array('id'=>3,'text'=>'blabla3'),
'd'=>array('id'=>4,'text'=>'blabla4'),
);
and i want to sort the above array by the keys a,b,c,d, who exist in another array:
$tempArray=array('c','a','d','b');
How can I do that so the $myArray
looks like this:
$myArray=array(
'c'=>array('id'=>3,'text'=>'blabla3'),
'a'=>array('id'=>1,'text'=>'blabla1'),
'd'=>array('id'=>4,'text'=>'blabla4'),
'b'=>array('id'=>2,'text'=>'blabla2'),
);
thanks for helping me!
The simplest and likely most efficient way to do this is by iterating the array that holds the sort order and creating a new, sorted array:
$sorted = array();
foreach ($tempArray as $order) {
if (isset($myArray[$order])) {
$sorted[$order] = $myArray[$order];
}
}
print_r($sorted);
This works because associative arrays implicitly have an order of the order in which elements were added to the array.
See it working
EDIT
Any solution involving a sorting function will likely be much less efficient than this. This is because in order to do it you will need to use a function that takes a callback - this already has an implied overhead of the function call.
The sorting functions also work by comparing items, meaning that the complexity any of those solutions will be greater than that of this solution (the complexity of this is simply O(n)). Also, in order to derive the return value for the sorting function you would need to inspect the target array, finding the position of each of the keys being compared, for each comparison, adding even more complexity.
I have a numeric array with codes like this: array('123', '333', '444');
I also have a function that given a code returns a name, so myFunc('123') would return 'soap'
I'd like to generate an associative array containing codes as keys and names as values. Is there any function that would allow me to do this? I know a foreach loop would do it but I wonder if there's some made function for this. Saw some methods like array_map but they don't seem to fit my needs.
array_combine($arr, array_map('myFunc', $arr))
But two functions, not one ;-) Still oneliner though
I want to convert PHP list (array), i.e.
array("start", "end", "coords")
into associative array with truthy values (just to be able to test the presence/absence of key quickly), i.e. to something like this:
array(
"start" => 1,
"end" => 1,
"coords" => 1
)
Is there any more elegant way to do it than this?
array_fill_keys($ar, 1)
There is probably no more elegant solution than array_fill_keys($ar, 1).
There is a function called array_flip that does this.
http://php.net/array_flip
Doing array_flip on an array and then using isset turned out to be much faster than doing in_array for me.
But note that this is only useful when you're going to be searching the array multiple times.