Reverse alphabetic sort multidimensional PHP array maintain key - php

I'm dying here, any help would be great.
I've got an array that I can sort a-z on the value of a specific key but cannot sort in reverse z-a.
sample of my array which i'd like to sort by ProjectName (z-a):
Array
(
[0] => Array
(
[count] => 1
[ProjectName] => bbcjob
[Postcode] => 53.471922,-2.2996078
[Sector] => Public
)
[1] => Array
(
[count] => 1
[ProjectName] => commercial enterprise zone
[Postcode] => 53.3742081,-1.4926439
[Sector] => Public
)
[2] => Array
(
[count] => 1
[ProjectName] => Monkeys eat chips
[Postcode] => 51.5141492,-0.2271227
[Sector] => Private
the desired results would be to maintain the entire array key -> value structure but with the order:
Monkeys eat chips
Commericial enterprise zone
bbcjob
I hope this makes sense

This is a job for usort which lets you define a function to do your comparison and then sort the array based on that.
function cmp($a, $b)
{
return strcmp($b["ProjectName"], $a["ProjectName"]);
}
usort($yourArray, "cmp");
print_r($yourArray);
Edit: based on your comment, you should just reverse the $x and $y in your function to reverse the order of the sorting performed.
function name_sort($x, $y)
{
return strcasecmp($y['ProjectName'], $x['ProjectName']);
}

Related

Sort an array (looking a specific value) based on another array

I have this array of options, and some value of an internal array is the "ID"
[options] => Array (
[0] => Array (
[id] => 1088
[label] => John
)
[1] => Array (
[id] => 1089
[label] => Peter
)
[2] => Array (
[id] => 1050
[label] => Mary
)
....
On the other hand, I have this array:
$array_sort = array(1089, 1050, 1088, ...);
I would like the options array of the first array is sorted (looking the "id") based on the $array_sort.
I know how to do it in a very dirty way (with a lot of loops and temporary arrays), but I guess there's some smart solution of array_* functions to do this.
Thank you !
You could use array_filter to limit the options to only those in the sorted array, then usort to sort them based on their position in the $array_sort array using array_search:
$sorted = array_filter($options, function($arr) use($array_sort) {
return in_array($arr['id'], $array_sort);
});
usort($sorted, function($a, $b) use($array_sort) {
return array_search($a['id'], $array_sort) - array_search($b['id'], $array_sort);
});
// $sorted should now be the sorted array

PHP, sort array of objects and remove item by object fields

I seen this post PHP, sort array of objects by object fields and it works great for me, but I need help one step further.
Here code sample
Array
(
[0] => stdClass Object
(
[ID] => 1
[name] => Mary Jane
[count] => 420
)
[1] => stdClass Object
(
[ID] => 2
[name] => Johnny
[count] => 234
)
[2] => stdClass Object
(
[ID] => 3
[name] => Kathy
[count] => 4354
)
....
I want to be able to remove array object that has count above 450. How could I do this? So basically it removes ([2] => stdClass Object) and etc.
Function I am using is this
function cmp($a, $b)
{
return strcmp($a->name, $b->name);
}
usort($your_data, "cmp")
So how could I go about doing this?
Do I use the unset($text) command to do this?
You can use array_filter() to remove items from array.
$arr = array( ... );
// sort array with your usort
...
// filter array to new one
$filteredArr = array_filter($arr, function($item) {
return $item->count <= 450;
});
You can't use usort() to remove members from the array being sorted. Your best bet would be to first use array_filter() to remove the objects with counts above 450, then sort the result.

Sort an array according to a set of values from another array

I am aware there is another question on SO which is supposed to answer the same thing. My problem is that I don't see what array merge has do do with anything. I don't want to merge the arrays necessarily and I don't understand how that would help ordering them ... also I don't understand where the ordering is coming into it.
If it is relevant could someone please explain in a bit more detail whether the other answer would work for me or not and how
Here is what I have ( the array is quite large so this is a simplification )
Essentially I have something like this
Array (
[0] => stdClass Object (
[term_id] => 72
[name] => name
[slug] => slug
[term_group] => 0
[term_order] => 1
[term_taxonomy_id] => 73
[taxonomy] => gallery_category
[description] => description
[parent] => 78
[count] => 85 )
[1] => stdClass Object (
[term_id] => 77
[name] => name
[slug] => slug
etc, etc, etc, there are a lot of objects in the array
Then I have an ordering array like
Array (
[0] => 77,
[1] => 72,
etc
So what I want to do is to impose the ordering of the second array on the first one - the ordering array holds the value of the [term_id] from the second array in the corrrect order. In the example above that would mean that I would reverse the order of the first two objects.
$order_array = [77, 72];
$order_array = array_flip($order_array);
usort($objects, function($a, $b) use ($order_array)
{
return $order_array[$a->term_id] - $order_array[$b->term_id];
});
This assumes that $order_array has an entry for every term_id.
uksort could do it.
function cmp($a, $b)
{
$ordering_array=array(0=>77, 1=>72);
return $ordering_array[$a] - $ordering_array[$b];
}
$a = array() #etc...
uksort($a, "cmp");

PHP: Sorting Multi-Array Result [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I sort a multidimensional array in php
Array ( [0] => Array (
[card_name] => CardA
[str] => 10
[def] => 10
[desc] => - Recover 150 points of vitality
- Attack twice"
[qty] => 5
)
[1] => Array (
[card_name] => CardD
[str] => 40
[def] => 40
[desc] => - Investigate enemy's weakpoint
[qty] => 3
)
[2] => Array ( [card_name] => CardG
[str] => 35
[def] => 20
[desc] =>
[qty] => 1
)
[3] => Array (
[card_name] => CardH
[str] => 25
[def] => 30
[desc] =>
[qty] => 1
)
[4] => Array (
[card_name] => CardI
[str] => 15
[def] => 40
[desc] => - Enhance strength
[qty] => 1
)
[5] => Array (
[card_name] => CardJ
[str] => 5
[def] => 50
[desc] => - Make silence
[qty] => 3
)
)
I have a simple question about sorting arrays. I just want to sort the array in either by str or def in either asc or desc. The examples in the php.net is a bit confusing and I was wondering if anyone can solve this small dilemma.
I know I should be using array_multi_sort for this.
Thanks.
Use the usort function. It will be something like this in your case :
function compare($valueA, $valueB) {
if ($valueA['str'] > $valueb['str']) {
return 1;
} else if ($valueA['str'] < $valueb['str']) {
return -1;
}
return 0;
}
usort($yourArray, "compare");
Try php usort - http://www.php.net/manual/en/function.usort.php
I've not tried and run the code but it'll be something below:
function cmp($a, $b)
{
return strcmp($a['def'],$b['def'])
}
$a = yourArray[];
usort($a, "cmp");
This will iterate through each element and pass the array element as a parameter and will use your custom function to sort.
usort() and strnatcmp() is your solution:
<?php
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
usort($array, build_sorter('def'));
print_r($array);
?>
It will sort all arrays by your defined key.
Array multisort requires you to build an array holding the values of the keys you want to sort by to do what you want, but with the same first dimension keys of the original array.
Thus if you make an array which holds 0 => 10, 1 => 5... etc where those are the values for str or def for keys 0 and 1, then you can do
foreach($originalArray as $key => $record) {
$keyValuesArray[$key] = $record['str'];
}
array_multisort($keyvaluesArray, SORT_ASC, $originalArray);
And original array would be modified to be sorted.
As for what you should be doing, I don't think array multisort is "the way" to do it, but is not a terrible way of doing it. Other solutions might be slightly more efficient.

How to sort the following array?

I am fetching records from database which returns an array as follows:
Array
(
[0] => stdClass Object
(
[id] => 2
[name] => ravi
[text] => hey
[date] => 2011-05-1
)
[1] => stdClass Object
(
[id] => 3
[name] => shiv
[text] => bye
[date] => 2011-04-29
)
[2] => stdClass Object
(
[id] => 4
[name] => adi
[text] => hello
[date] => 2011-04-30
)
)
How to sort this based on the date element?
You should sort this before you actually fetch it, meaning use the 'ORDER BY' clause already in your database query!
Why?
because you write much less code
because it is faster
because it is easier to refactor
You may find the usort() function useful: http://docs.php.net/manual/en/function.usort.php
You could pass in as the second parameter the following function:
function cmp($a, $b)
{
if ($a->date == $b->date) {
return 0;
}
return ($a->date < $b->date) ? -1 : 1;
}
Ideally you should be sorting within the query itself, using ...ORDER BYdate..
..but if you really wanna do it with php, look at the user notes in the manual under sort, there are examples of how to sort like that (and you can apply with rsort() or asort() or arsort() depending on if you want to preserve keys or sort descending or whatever)

Categories