Jump to content

Sorting array


TomT

Recommended Posts

Hi

My array is made using :

$group[] = array("ctime"=>$ctime,"name"=>$name

that results in :

 

[4]=>
  array(2) {
    ["ctime"]=>
    int(1334597042)
    ["name"]=>
    string(7) "John.dat"
  }
  [3]=>
  array(2) {
    ["ctime"]=>
    int(1334935095)
    ["name"]=>
    string(4) "mark"
  }
  [2]=>
  array(2) {
    ["ctime"]=>
    int(1340634768)
    ["name"]=>
    string(7) "lol.txt"
  }
  [1]=>
  array(2) {
    ["ctime"]=>
    int(1334597041)
    ["name"]=>
    string( "dave.txt"
  }
  [0]=>
  array(2) {
    ["ctime"]=>
    int(1335193200)
    ["name"]=>
    string(4) "paul"
  }

 

How would I sort this array ascending based on  the ctime values ?

Thanks

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

Here's an actual working solution

 

<?php

$array = array(
array( 'id'=>24, 'name'=>'foo' ),
array( 'id'=>13, 'name'=>'bar' ),
array( 'id'=>18, 'name'=>'baz' ),
);

function custom_sort($a, $b) {
return $a['id'] - $b['id'];
}

usort($array, 'custom_sort');

var_dump($array);

?>

returns

array
  0 => 
    array
      'id' => int 13
      'name' => string 'bar' (length=3)
  1 => 
    array
      'id' => int 18
      'name' => string 'baz' (length=3)
  2 => 
    array
      'id' => int 24
      'name' => string 'foo' (length=3)

Link to comment
https://forums.phpfreaks.com/topic/264763-sorting-array/#findComment-1356934
Share on other sites

Yes, reversing $a and $b gives descending sort.

 

AFAIK just using sort() on a 2D array will sort on the the first element eg

 

<?php
    $a = array(
        array( 'x' => 20, 'y' => 'ab'),
        array( 'x' => 30, 'y' => 'cd'),
        array( 'x' => 10, 'y' => 'ef')
    );
    
    sort($a);
    
    echo '<pre>'.print_r($a, 1).'</pre>';
?>

-->

Array
(
    [0] => Array
        (
            [x] => 10
            [y] => ef
        )

    [1] => Array
        (
            [x] => 20
            [y] => ab
        )

    [2] => Array
        (
            [x] => 30
            [y] => cd
        )

)

Link to comment
https://forums.phpfreaks.com/topic/264763-sorting-array/#findComment-1357023
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.