Frage

i am having an array like this

Array
(
    [A] => Array
        (
            [0] => 1
            [1] => XYZ
        )

    [B] => Array
        (
            [0] => 2
            [1] => ABC
        )

    [C] => Array
        (
            [0] => 0
            [1] => DEF
        )

    [D] => Array
        (
            [0] => 3
            [1] => GHI
        )

    [E] => Array
        (
            [0] => 0
            [1] => JKL
        )

)

I want to sort this array based on the numeric value present in 0th position.. Can anyone help me to solve this? Thanks in advance.

War es hilfreich?

Lösung

Use usort for a custom sorting method. http://nl1.php.net/manual/en/function.usort.php

<?php
function cmp($a, $b)
{
    if ($a[0] == $b[0]) {
        return 0;
    }
    return ($a[0] < $b[0]) ? -1 : 1;
}

// your array
$a = array( 
    'a' => array(0 => 1, 1 => 'XYZ'), 
    'b' => array(0 => 0, 1 => 'ABC')
);

usort($a, "cmp");

Andere Tipps

I have made a usort based function for this exact purpose, so I though't I'd share it with you :)

/**
 * Sort a 2 dimension array with values in the second dimension
 *
 * Developer: chazmead89@gmail.com  // @RaggaMuffin-4201
 * 
 * Order can be string of a field, which will default to asc
 * OR as array(field1,field2...fieldn) each defaulting to asc
 * OR as assoc array(field1 => dir[asc|desc], field2 => dir[asc|desc]...fieldn
 * => dir[asc|desc])
 *
 * PHP Sort constants can be used: SORT_ASC | SORT_DESC
 *
 * @param array $array array to sort - passed by reference
 * @param mixed $order
 * @return null
 */
function multisort(&$array,$order) {

    usort($array, function($a,$b) use ($order) {
      $sortMap = array('asc'=>SORT_ASC,'desc'=>SORT_DESC);

      $aObj = (object)$a;
      $bObj = (object)$b;

      if (is_string($order))
        $order = array($order);

      if (is_object($order))
        $order = (array)$order;

      $i = 0;
      $cOrder = count($order);

      foreach($order as $field => $dir) {
        if (is_numeric($field)) {
          $field = $dir;
          $dir = SORT_ASC;
        }

        // Goto next step when a mis-match is found.
        if ($aObj->$field != $bObj->$field)
          break;

        // All fields match return 0
        if (++$i === $cOrder)
          return 0;
      }

      if(!is_numeric($dir)) {
        $dir = strtolower($dir);
        $dir = $sortMap[$dir];
      }

      $d = ($dir === SORT_DESC) ? -1 : 1;
      $c = ($aObj->$field < $bObj->$field) ? -1 : 1;

      return $c*$d;
    });
}

Here it is on Gist: https://gist.github.com/chazmead/8829079

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top