Phil Harmonie
Phil Harmonie

Reputation: 75

sort second level Array

i have this Array:

Array
(
    [0] => Array
        (
            [kw] => 46
            [anzahl_betten] => 100
        )

    [1] => Array
        (
            [kw] => 47
            [anzahl_betten] => 100
        )

    [2] => Array
        (
            [kw] => 45
            [anzahl_betten] => 100
        )

)

I want to sort it in "kw" order. I then want to go through the Array with foreach($array as $output) und the Array with kw 45 should be Array[0].

Upvotes: 1

Views: 1821

Answers (4)

shafi
shafi

Reputation: 310

    $a=array(array('kw'=>46,'anzahl_betten'=>100),array('kw'=>47,'anzahl_betten'=>100),array('kw'=>45,'anzahl_betten'=>100));
sort($a);
foreach($a as $x=>$x_value)
    {
print_r($x_value);  

   }

Upvotes: 0

arun
arun

Reputation: 3677

function subval_sort($a,$subkey) {
    $c = array();
    $b = array();
    foreach($a as $k=>$v) {
        $b[$k] = strtolower($v[$subkey]);
    }
    asort($b);
    foreach($b as $key=>$val) {
        $c[] = $a[$key];
    }
    return $c;
}

and then

$output = subval_sort($array_name,'kw'); 

Upvotes: 0

Manolo
Manolo

Reputation: 26370

Maybe this would work for you:

ksort($array);

Upvotes: 0

Alma Do
Alma Do

Reputation: 37365

Use usort() for that:

//$array is your array
usort($array, function($x, $y)
{
   return $x['kw']<$y['kw']?-1:$x['kw']!=$y['kw'];
});

Upvotes: 2

Related Questions