简体   繁体   中英

Sort array by key value

So I have this array.

Array
(
    [0] => Array
        (
            [key_1] => something
            [type] => first_type
        )

    [1] => Array
        (
           [key_1] => something_else
           [type] => first_type
        )

    [2] => Array
        (
            [key_1] => something_else_3
            [type] => second_type
        )

    [3] => Array
        (
            [key_1] => something_else_4
            [type] => second_type
        )
)

I have to sort by type value in a pattern like this:

first_type
second_type
first_type
second_type

My questions is, how can I do this?

Thanks a lot!

You need to use usort with a custom comparison function that compares the key_1 sub-keys of each item (you can use strcmp to do this conveniently). Assuming you do not want to change the structure of the resulting array, it would look something like this:

$arr = /* your array */
usort($arr, function($a, $b) { return strcmp($a['key_1'], $b['key_1']); });

如果sort()及其相关替代方法不起作用,则必须使用带有自定义函数的usort()uasort()对该数组进行排序。

So here's how I got it to work:

function filter_by_value($array, $index, $value) { 
    if(is_array($array) && count($array) > 0)  { 
        foreach(array_keys($array) as $key){ 
            $temp[$key] = $array[$key][$index]; 
            if ($temp[$key] == $value){ 
                $newarray[$key] = $array[$key]; 
            } 
        } 
    } 
    return $newarray;
}
$array = /* array here */ 
$type1 = array_values(filter_by_value($array, 'type', '1'));
$type2 = array_values(filter_by_value($array, 'type', '2'));
$i = 1; $x = 1; $y = 1;
$sorted = array();
foreach ($array as $a) {
    if ($i % 2) {
        $sorted[$i-1] = $type1[$x-1];
        $x++;
    } else {
        $sorted[$i-1] = $type2[$y-1];
        $y++;
    }
    $i++;
}

Found filter_by_value() on php.net but I don't remember where so, that's not made by me. Maybe this is not the best solution but it works pretty fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM