How to sort the following array? - php

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)

Related

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.

Reverse alphabetic sort multidimensional PHP array maintain key

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']);
}

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");

How should I sort this array by key with usort?

I think I might have read every usort article on StackOverflow, but I can't work out this one. It might be that usort is not the tool I need? Here's a bit of the array that I'm working with (I have it assigned to $allPages):
Array
(
[0] => Page Object
(
[id] => 4
[slug] => articles
[created_on] => 2009-08-06 07:16:00
)
[1] => Page Object
(
[id] => 99
[slug] => a-brief-history
[created_on] => 2011-04-25 12:07:26
)
[2] => Page Object
(
[id] => 98
[slug] => we-arrive
[created_on] => 2011-04-24 13:52:35
)
[3] => Page Object
(
[id] => 83
[slug] => new-year
[created_on] => 2011-01-02 14:05:12
)
)
I am trying ultimately to sort on the created_on value, but for the moment, I'd settle on being able to sort on any of them! When I try the normal cmp($a, $b) type callback with usort -- as, for example, in this answer on a usort question -- I just get a blank. Example:
function cmp($a, $b) {
return strcmp($a["slug"], $b["slug"]);
}
usort($allPages, 'cmp')
And print_r gives me nothing. This is with PHP 5.2.n, not 5.3 btw.
Guidance, please? And thankyou!
Your items in the array are objects, not associative arrays, so you need to refer to them like this:
function cmp($a, $b) {
return strcmp($a->slug, $b->slug);
}
usort($allPages, 'cmp')
Your dump of the array says that the elements are Page Objects, not arrays. By chance, do you need to say $a->created_on instead of $a['created_on']? Using object notation instead of array notation.
Just guessing...
As #Tesserex suggests, you need to use object notation instead of array notation.
If you had notices turned on, you'd get error messages about accessing an object as an array.
Another thing to consider, is, your Pages don't all have a 'created_on' attribute, some have a 'published_on' attribute. You'll have to do some error checking / logic inside your usort method to make sure that the key you want to sort by is available, and do something when it's not.

Sorting Multidimensional Array

Thought I will point out first that I have looked around on Stackoverflow and the internet already and although they are plenty of examples none of them are explained into such a way for me to understand how to convert the code to work with my array structure.
I believe I need to use one of the functions uksort or uasort but unsure on this as well.
My array looks like the following.
Array
(
[0] => Array
(
[Result] => Array
(
[id] => 260
[event_id] => 72
[year] => 2010
[york_score] => 27
[york_points] => 0.0
[lancs_score] => 51
[lancs_points] => 4.0
[winner] => L
[confirmed] => Y
[updated] => 2010-05-01 16:10:03
)
[Event] => Array
(
[id] => 72
[sport_id] => 25
[event_title] => 1st Team
[Sport] => Array
(
[id] => 25
[sport_title] => Netball
)
)
)
And where its [0] means it continues on.
I need to sort all of the arrays [0,1,2,3,...] by the sport_title key found in [Event][Sport]
Does anyone know how to create a sorting function to do this?
Some explanation of how the function is working would also be helpful if I later need to adapter/alter the code to work else where on my site.
Where $array is the name of the array which holds the array you posted in your question.
function sort_multi($item_1, $item_2)
{
// strcmp looks at two strings and, based off the characters' and their order,
// determines which one is numerically greater. When this function returns a
// negative, for example, it means the first item it's comparing is less that the
// second item (ef and eg, for example). The usort function then rearranges
// the array based off these comparisons.
return strcmp($item_1['Event']['Sport']['sport_title'], $item_2['Event']['Sport']['sport_title']);
}
usort($array, 'sort_multi');

Categories