包含下划线的数组字段上的PHP多重排序

时间:2014-04-27 01:49:28

标签: php arrays substring delimiter array-multisort

我有一个这样的数组:

$data[] = array('ALT_ID' => '202143_N', 'bmi' => 2.5);
$data[] = array('ALT_ID' => '202144_P', 'bmi' => 1.2);
$data[] = array('ALT_ID' => '202145_N', 'bmi' => 6.6);
$data[] = array('ALT_ID' => '202146_P', 'bmi' => 3.6);
$data[] = array('ALT_ID' => '202147_N', 'bmi' => 7.6);
$data[] = array('ALT_ID' => '202148_P', 'bmi' => 8.6);

如何对ALT_ID(N到P)和bmi(从低到高)进行排序以得到这样的数组:

array (
array('ALT_ID' => '202143_N', 'bmi' => 2.5),
array('ALT_ID' => '202145_N', 'bmi' => 6.6),
array('ALT_ID' => '202147_N', 'bmi' => 7.6),
array('ALT_ID' => '202144_P', 'bmi' => 1.2),
array('ALT_ID' => '202146_P', 'bmi' => 3.6),
array('ALT_ID' => '202148_P', 'bmi' => 8.6)
)

这是我尝试过的,而不是以所需格式提供输出:

演示链接:https://eval.in/142639

<?php
$data[] = array('ALT_ID' => '202143_N', 'bmi' => 2.5);
$data[] = array('ALT_ID' => '202144_P', 'bmi' => 1.2);
$data[] = array('ALT_ID' => '202145_N', 'bmi' => 6.6);
$data[] = array('ALT_ID' => '202146_P', 'bmi' => 3.6);
$data[] = array('ALT_ID' => '202147_N', 'bmi' => 7.6);
$data[] = array('ALT_ID' => '202148_P', 'bmi' => 8.6);

foreach ($data as $key => $row) {
    $volume[$key]  = $row['ALT_ID'];
    $bmi[$key] = $row['bmi'];
}

array_multisort($volume, SORT_ASC, SORT_STRING, $bmi, SORT_ASC, $data);

print_r($data);
?>

谢谢。

2 个答案:

答案 0 :(得分:2)

使用usort()会更容易:

$data = array();
$data[] = array('ALT_ID' => '202143_N', 'bmi' => 2.5);
$data[] = array('ALT_ID' => '202144_P', 'bmi' => 1.2);
$data[] = array('ALT_ID' => '202145_N', 'bmi' => 6.6);
$data[] = array('ALT_ID' => '202146_P', 'bmi' => 3.6);
$data[] = array('ALT_ID' => '202147_N', 'bmi' => 7.6);
$data[] = array('ALT_ID' => '202148_P', 'bmi' => 8.6);

usort($data, function($a, $b){
$x = substr(strrchr($a['ALT_ID'], '_'), 1);
$y = substr(strrchr($b['ALT_ID'], '_'), 1);
if($x == $y) return $a['bmi']-$b['bmi'];
return strcmp($x, $y);
});

print_r($data);

DEMO

答案 1 :(得分:1)

您需要将ALT_ID的最后一个字符添加到排序键中。

<?php

$data[] = array('ALT_ID' => '202143_N', 'bmi' => 2.5);
$data[] = array('ALT_ID' => '202144_P', 'bmi' => 1.2);
$data[] = array('ALT_ID' => '202145_N', 'bmi' => 6.6);
$data[] = array('ALT_ID' => '202146_P', 'bmi' => 3.6);
$data[] = array('ALT_ID' => '202147_N', 'bmi' => 7.6);
$data[] = array('ALT_ID' => '202148_P', 'bmi' => 8.6);

foreach ($data as $key => $row) {
    $pieces = explode('_',$row['ALT_ID']);
    $id_piece = $pieces[1];
    $volume[$key]  = $id_piece . $row['ALT_ID'];
    $edition[$key] = $row['bmi'];
}

//edit
array_multisort($volume, SORT_ASC, $edition, SORT_DESC, $data);

print_r($data);

?>