简体   繁体   English

多数组排序PHP

[英]Multi Array Sort PHP

I'm having some problems wrapping my head around how to do this. 我在解决此问题时遇到了一些问题。 I have an array in PHP 我在PHP中有一个数组

    array(131) {
     ["BLANF     "]=>
      array(3) {
        ["line_3"]=>
        string(4) "3.92"
        ["line_1"]=>
        string(1) "6"
        ["line_2"]=>
        string(2) "14"
      }
      ["BLOOH     "]=>
      array(3) {
        ["line_3"]=>
        string(4) "2.00"
        ["line_1"]=>
        string(1) "20"
        ["line_2"]=>
        string(1) "6"
      }

}

That I need to sort based on the value of line_1. 我需要根据line_1的值进行排序。 In PHP Thanks Zachary 在PHP中感谢Zachary

通过提供比较回调函数来比较适当的行的值,从而使用uasort

You have to create a custom comparison function for your array and employ it with uasort() to maintain the indices of the array. 您必须为数组创建一个自定义比较函数,并将其与uasort()以维护数组的索引。

Here is how you can use uasort() to sort by line_1 ... It's simple to change to sort by any other key in the nested array. 这是如何使用uasort()line_1排序的方法。更改嵌套数组中的任何其他键很简单。

<?php

  // The custom comparison function
function cmp($a, $b)            
{
    if ($a["line_1"] == $b["line_1"]) {
        return 0;
    }
    return ($a["line_1"] < $b["line_1"]) ? -1 : 1;
}

  // Sort the array using your custom comparison
uasort($array, 'cmp');

  // Make sure we got the right result
print_r($array);
?>

Live Example 现场例子

(I changed the line_1 numbers so that the sort actually does something) (我更改了line_1数字,以便排序实际上可以执行某些操作)

In this case PHP will juggle the types for you, but you should watch out for the fact that you have strings and are converting them to numbers. 在这种情况下,PHP会为您处理各种类型,但是您应该注意以下事实:您拥有字符串并将其转换为数字。 If you're not sure what will happen then cast the strings to floats or ints. 如果您不确定会发生什么,则将字符串转换为浮点数或整数。 This is important since, PHP can compare strings alphabetically with the comparison operators .... so, if there's any chance that a letter or comma or something can sneak into your array value then you can type cast to an int ( (int) $a["line_1"] ) or a float ( (float) $a["line_1"] ). 这很重要,因为PHP可以使用比较运算符按字母顺序比较字符串 ....因此,如果有可能字母或逗号或其他内容会潜入您的数组值中,则可以将类型转换为int( (int) $a["line_1"] )或浮点数( (float) $a["line_1"] )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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