如何使用指定的值序列对关联数组进行排序?

时间:2016-06-10 15:06:53

标签: php

我想用指定的值序列

对关联数组进行排序
$arr=array(array("company"=>"A", "revenue_range"=>"10-100M"),
      array("company"=>"B", "revenue_range"=>"0-10M"),
      array("company"=>"C", "revenue_range"=>"10-100M"),
      array("company"=>"D", "revenue_range"=>"100M-1B"),
      array("company"=>"E", "revenue_range"=>">1B"),
     array( "company"=>"F", "revenue_range"=>"0-10M")

);

结果: -

$arr=array(array("company"=>"B", "revenue_range"=>"0-10M"),
       array( "company"=>"F", "revenue_range"=>"0-10M"),
      array("company"=>"A", "revenue_range"=>"10-100M"),
      array("company"=>"C", "revenue_range"=>"10-100M"),
      array("company"=>"D", "revenue_range"=>"100M-1B"),
      array("company"=>"E", "revenue_range"=>">1B"));

2 个答案:

答案 0 :(得分:1)

<?php
    $arr = array( 
        array("company"=>"A", "revenue_range"=>"100 - 250M"), 
        array("company"=>"B", "revenue_range"=>"10 - 50M"), 
        array("company"=>"C", "revenue_range"=>"500M - 1B"), 
        array("company"=>"D", "revenue_range"=>"50 - 100M"), 
        array("company"=>"E", "revenue_range"=>">1B"), 
        array("company"=>"F", "revenue_range"=>"1 - 10M"), 
        array("company"=>"G", "revenue_range"=>"0 - 1M") 
        ); 
    $order= array("0 - 1M", "1 - 10M", "10 - 50M", "50 - 100M", "100 - 250M", "250 - 500M", "500M - 1B", ">1B");
    $order_by=array_flip($order);
    usort($arr, function($a, $b) use($order_by) {
        return $order_by[$a["revenue_range"]] - $order_by[$b["revenue_range"]];
    });
    echo "<pre>";
    print_r($arr);

答案 1 :(得分:-1)

您可以使用usort并传递一个比较函数,该函数指定revenue_range字符串的数值(即&#34; 0-10M&#34;是1和&#34; 10-100M&#34;是2,...和&#34;&gt; 1B&#34;是5,然后你最终得到&#34;&gt; 1B&#34;&gt;&#34; 0-10M&#34;)。