Sort Multi-dimensional array by decimal values

自闭症网瘾萝莉.ら 提交于 2019-11-29 14:00:53
$arr = array(
    array('company' => 'A', 'weight' => 4.6),
    array('company' => 'B', 'weight' => 1.7),
    array('company' => 'C', 'weight' => 3.7),
);

usort($arr, 'order_by_weight');

function order_by_weight($a, $b) {
    return $b['weight'] > $a['weight'] ? 1 : -1;
}

var_dump($arr);

PS: it's not a rocket science - this exact "trick" is used as the first example at http://php.net/usort

You can do this with anonymous function in just one line

$arr = array(
    array('company' => 'A', 'weight' => 4.6),
    array('company' => 'B', 'weight' => 1.7),
    array('company' => 'C', 'weight' => 3.7),
);
usort($arr, function($a, $b) { return $b['weight'] > $a['weight'] ;});

print_r($arr);

Hope this helps :)

You can sort the array using array_multisort, altough, this is often used to sort on multiple array values instead of one.

echo "<pre>";

 $a = array(
     array('company' => 'ebay', 'weight' => 4.6), 
     array('company' => 'ebay', 'weight' => 1.7),
     array('company' => 'ebay', 'weight' => 3.7),
     array('company' => 'ebay', 'weight' => 2.7),
     array('company' => 'ebay', 'weight' => 9.7),
     array('company' => 'ebay', 'weight' => 0.7),
 );

 $company = array();
 $weight = array();

 foreach($a as $key=>$val) {
     array_push($company, $val['company']);
     array_push($weight, $val['weight']);
 }

 array_multisort($weight, SORT_ASC, $a);

 print_r($a);

As sorting algo here is good example for sort multi dimension array without using any more inbuilt php function

$multiarr = array('0'=>array(
        "hashtag" => "a7e87329b5eab8578f4f1098a152d6f4",
        "title" => "Flower",
        "order" => 3),

'1' => array(
        'hashtag' => "b24ce0cd392a5b0b8dedc66c25213594",
        "title" => "Free",
        "order" => 2),
'2' => array('hashtag' => 'e7d31fc0602fb2ede144d18cdffd816b',
        'title' => 'Ready',
        'order' => 1
    ));

sorting function :

    function multisort (&$array, $key) {
$valsort=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
    $valsort[$ii]=$va[$key];
}
asort($valsort);
foreach ($valsort as $ii => $va) {
    $ret[$ii]=$array[$ii];
}
$array=$ret;

}

multisort($multiarr,"order")enter code here

: output :

Array
 (
[2] => Array
    (
        [hashtag] => e7d31fc0602fb2ede144d18cdffd816b
        [title] => Ready
        [order] => 1
    )

[1] => Array
    (
        [hashtag] => b24ce0cd392a5b0b8dedc66c25213594
        [title] => Free
        [order] => 2
    )

[0] => Array
    (
        [hashtag] => a7e87329b5eab8578f4f1098a152d6f4
        [title] => Flower
        [order] => 3
    )

)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!