1

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].

0

4 Answers 4

2

Use usort() for that:

//$array is your array
usort($array, function($x, $y)
{
   return $x['kw']<$y['kw']?-1:$x['kw']!=$y['kw'];
});
Sign up to request clarification or add additional context in comments.

4 Comments

It's looking great. :)
@AshwiniAgarwal there's also return $x['kw']-$y['kw'] option as even more short and simple way to do this, but I prefer implicit -1/0/1 values
For information, if you got an "associative" array (with others keys than standard 0, 1, 2 ...), use uasort function to save keys. And bare in mind a closure function is used here, available only from php 5.3.X
Agreed. But this is non-assotiative array. For 5.x <= 5.2 there's create_function()
0

Maybe this would work for you:

ksort($array);

Comments

0
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'); 

2 Comments

You don't take array parameter by reference, and just return the new array in your function. So, if you only call your function without storing the return in a variable, it justs do nothing. BTW $b and $c are not declared
sorry that was copied content ;)
0
    $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);  

   }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.