Page 1 of 1

[Solved] Merging 2 arrays, then sorting it by a key

Posted: Tue Mar 20, 2007 6:41 pm
by Zoxive
Alright, I've been searching around for a while now, and still can't seem to find how to sort my multidimensional array by they key of 'score'.

The answer is probably right under my nose, but i still can't see to find it, i searched on google, and php.net, theres lots of array sorting functions, but i couldn't find one for they way i want to do it.

Heres what i have. (All my info is being pulled from my database, so i made an example up quick)

Code: Select all

<?php

$get[]=array('Name' => 'testing123','Url_Url' => 'testing123','Type' => 'Venues','score' => 1.5);
$get[]=array('Name' => 'testing1','Url_Url' => 'testing1','Type' => 'Venues','score' => 1);
$get2[]=array('Name' => 'Test','Url_Url' => 'test','Type' => 'Bands','score' => 2);
$get2[]=array('Name' => 'Test2','Url_Url' => 'test2','Type' => 'Bands','score' => .67);

$get = array_merge($get,$get2);
//No idea what array "sort" to use, but i need something like - sort($get,'score',SORT_ASC);
// 'score' being the key i want to sort by.
print '<pre>';
print_r ($get);
print '</pre>';

?>
I might have to end up making some kind of funky function.

Hope someone can help : p

-Zoxive

Posted: Tue Mar 20, 2007 6:46 pm
by stereofrog
Look at array_multisort or usort.

OT: how you guys make those fancy manual links? [ fphp ] doesn't seem to work.

Posted: Tue Mar 20, 2007 6:54 pm
by Zoxive
I figured it out 1 minute after i posted : /
I was still searching and under

Code: Select all

array_multisort
theres an example for want i wanted, and works fine.

Code: Select all

<?php

$get[]=array('Name' => 'testing123','Url_Url' => 'testing123','Type' => 'Venues','score' => 1.5);
$get[]=array('Name' => 'testing1','Url_Url' => 'testing1','Type' => 'Venues','score' => 1);
$get2[]=array('Name' => 'Test','Url_Url' => 'test','Type' => 'Bands','score' => 2);
$get2[]=array('Name' => 'Test2','Url_Url' => 'test2','Type' => 'Bands','score' => .67);
$get = array_merge($get,$get2);

foreach($get as $key => $row){
	$score[$key] = $row['score'];
	$name[$key] = $row['Name'];
}

array_multisort($score, SORT_DESC, $name, SORT_DESC, $get);

print '<pre>';
print_r ($get);
print '</pre>';

?>
:oops: