Jump to content

sorting arrays


iversonm

Recommended Posts

so lets say you

$array=(array(13, 'apples', 'red'), array(15, 'orange', 'orange'), array(1, 'watermelon', 'green'));

 

if i want to sort $array by the number, how do i go about doing that basically i want

$array[0]=(1, 'watermelon', 'green')

$array[1]=(13, 'apples', 'red')

$array[2]=(15, 'orange', 'orange')

 

any ideas?

Link to comment
https://forums.phpfreaks.com/topic/125901-sorting-arrays/
Share on other sites

try this

<?php
function cust_sort($a,$b){
if($a[0]>$b[0])
	return 1;
elseif($a[0]<$b[0])
	return -1;
else
	return 0;
}
$array = array(array(13, 'apples', 'red'), array(15, 'orange', 'orange'), array(1, 'watermelon', 'green'));
echo "<pre>";
print_r($array);
usort($array,"cust_sort");
print_r($array);
?>

 

Scott.

Link to comment
https://forums.phpfreaks.com/topic/125901-sorting-arrays/#findComment-651069
Share on other sites

try this

<?php
function cust_sort($a,$b){
if($a[0]>$b[0])
	return 1;
elseif($a[0]<$b[0])
	return -1;
else
	return 0;
}
$array = array(array(13, 'apples', 'red'), array(15, 'orange', 'orange'), array(1, 'watermelon', 'green'));
echo "<pre>";
print_r($array);
usort($array,"cust_sort");
print_r($array);
?>

 

Scott.

 

simpler custom function

function cust_sort($a, $b)
{
    return $a[0] - $b[0];
}

 

But, as sasa said, if you are sorting on the first elements of the array then sort() will do it.

Link to comment
https://forums.phpfreaks.com/topic/125901-sorting-arrays/#findComment-651250
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.