Forum Moderators: coopster

Message Too Old, No Replies

question about sorting multi dimensional arrays

         

sneaks

9:03 pm on Nov 13, 2005 (gmt 0)

10+ Year Member



i am trying to krsort by date in a multi dim array. i hope i put this correctly (but i have included the php function i made for converting xml to array:

so each sub array is labelled according to the date which then in turn becomes the name of the key in the multi array, but when sorted, any duplicate dates are replaced by the most recent...


function index2array()
{
$dom = new DomDocument();
$dom->load(INDEX) or die('Failed to load ' . INDEX . '.');
global $mArray;
$items = $dom -> getElementsByTagName('item');
$dates = $dom -> getElementsByTagName('date');
$titles = $dom -> getElementsByTagName('title');
$links = $dom -> getElementsByTagName('link');
$descriptions = $dom -> getElementsByTagName('description');
$keywords = $dom -> getElementsByTagName('keywords');
$mArray=array();
$numberOfItems = $dates -> length;
for ($i = 0; $i < $numberOfItems; $i++)
{
$a_name = $dates -> item($i) -> textContent;
$$a_name = array
(
'id' => $items -> item($i) -> getAttribute('id'),
'title' => $titles -> item($i) -> textContent,
'link' => $links -> item($i) -> textContent,
'description' => $descriptions -> item($i) -> textContent,
'keywords' => $keywords -> item($i) -> textContent
);
$mArray[$dates -> item($i) -> textContent] = $$a_name;
}
}

i'm trying to make my own news CMS and wont actually have duplicate date entries in my xml but i still want it to be solid... thanks for any help!

cheers
snx

ergophobe

10:29 pm on Nov 13, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



check out array_multisort() [php.net]

It's a little funky to figure out and as arrays get very complex, I've found that it sometimes makes sense to break out one dimension, sort that, and then use that as a type of sorting key in the multisort. array_multisort seems like it was designed to sort in the opposite sense than I would expect, but with a bit of pondering it's very handy and fast.