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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.