Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: sortowanie tablocy według parametru
Forum PHP.pl > Forum > Przedszkole
Gość_obcy
Witam,

mam sobie tablicę:
Kod
        $results[$number]['title'] = $temp[2][$number];
        $results[$number]['url'] = $temp[3][$number];
        $results[$number]['description'] = $temp[4][$number];
        $results[$number]['status'] = $temp[5][$number];


Do tej tablicy wpisywane sa wartosci w petli,
jak mogę posortowac tablice $results według $results[$number]['status'] pola status ?

Pozdrawiam i dziękuję smile.gif
crash
  1. <?php
  2. function arraySort( $array, $arguments = array(), $keys = true )
  3. {
  4.    $code = '';
  5.    foreach( $arguments as $argument )
  6.    {
  7.       $field = substr( $argument, 2, strlen( $argument ) );
  8.       $type  = $argument[ 0 ];
  9.       $order = $argument[ 1 ];
  10.             
  11.       $code .= 'if( !is_numeric( $result ) or ( $result == 0 ) ) ';
  12.             
  13.       if( strtolower( $type ) == 'n' )
  14.       {
  15.          $code .= ( $order == '-' ) ? '$result = ( $a[ "'.$field.'" ] > $b[ "'.$field.'" ] ? -1 : ( $a[ "'.$field.'" ] < $b[ "'.$field.'" ] ? 1 : 0 ) );' : '$result = ( $a[ "'.$field.'" ] > $b[ "'.$field.'" ] ? 1 : ( $a[ "'.$field.'" ] < $b[ "'.$field.'" ] ? -1 : 0 ) );';
  16.       }
  17.       else
  18.       {
  19.          $code .= ( $order == '-' ) ? '$result = strcoll( $a[ "'.$field.'" ], $b[ "'.$field.'" ] ) * -1;' : '$result = strcoll( $a[ "'.$field.'" ], $b[ "'.$field.'" ] );';
  20.       }
  21.    }
  22.         
  23.    $code .= 'return $result;';
  24.  
  25.    $compare = create_function( '$a, $b', $code );
  26.     
  27.    if( $keys == true )
  28.    {
  29.       uasort( $array, $compare );
  30.    }       
  31.    else
  32.    {
  33.       usort( $array, $compare );
  34.    }
  35.         
  36.    return $array;
  37. }
  38.  
  39. $results = arraySort( $results, array( 's+status' ) ); // s - ciągi, n - liczby, -/+ - kolejność
  40. ?>
Gość_obcy
dzięki smile.gif
orson
witam ...

jest też wbudowana funkcja w php ... http://pl.php.net/array_multisort ... jeżeli to duże tablice to ona na pewno będzie wydajniejsza ...

pozdrawiam
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.