Web Hosting Talk







View Full Version : Question on array sorting in php


computerwiz3491
01-17-2008, 05:10 PM
I have the following array that I printed using print_r

[item] => Array
(
[0] => SimpleXMLElement Object
(
[title] => Title 1
[link] => Link 1
[description] => Description 1
[guid] => guid 1
[pubDate] => 9
)

[1] => SimpleXMLElement Object
(
[title] => Title 2
[link] => Link 2
[description] => Description 2
[guid] => guid 2
[pubDate] => 10
)
)


I need to be able to sort it by [pubDate] in highest to lowest order.

How would I do this?

Thanx

Codebird
01-17-2008, 06:35 PM
you can use your pubDate as Key and then ksort($item);

computerwiz3491
01-17-2008, 09:33 PM
It's a multi-dimensional array which has to stay in the same format.

foobic
01-17-2008, 09:54 PM
You still need to do as Hicham suggested: create an additional array keyed on pubDate containing the same objects. Ideally you do this at the same time as creating your original array; if not you'll have to iterate through the original, eg. using array_map.

bigfan
01-17-2008, 10:19 PM
Use array_multisort() (http://us.php.net/manual/en/function.array-multisort.php):foreach ($my_array as $key => $val) {
$tmp[$key] = $val['pubDate'];
}
array_multisort($tmp, SORT_DESC, $my_array);That should work on the array as shown. (Although I think there's more to it than what you posted. If so adjust the keys for the values of $val assigned to $tmp as needed.)

bigfan
01-18-2008, 11:39 AM
Assume an XML document like this:<rss>
<channel>
<title>Test Doc</title>
</channel>
<item>
<title>Title 1</title>
<link>Link 1</link>
<description>Description 1</description>
<guid>guid 1</guid>
<pubDate>9</pubDate>
</item>
<item>
<title>Title 2</title>
<link>Link 2</link>
<description>Description 2</description>
<guid>guid 2</guid>
<pubDate>10</pubDate>
</item>
</rss>Then this code:$xml_obj = simplexml_load_file('doc.xml');
$my_array = $xml_obj->xpath('item');
foreach ($my_array as $key => $val) {
$val = (array) $val; // Notice explicit cast.
$tmp[$key] = $val['pubDate'];
}
array_multisort($tmp, SORT_DESC, $my_array);will give you this:Array
(
[0] => SimpleXMLElement Object
(
[title] => Title 2
[link] => Link 2
[description] => Description 2
[guid] => guid 2
[pubDate] => 10
)
[1] => SimpleXMLElement Object
(
[title] => Title 1
[link] => Link 1
[description] => Description 1
[guid] => guid 1
[pubDate] => 9
)
)