「PHP入門」多次元配列をソートするサンプル

2018年5月5日

phpコード
function multiarray_Compare($a, $b)
{
$val_arr = array(
'gold’=>’asc’,
'silver’=>’desc’
);
foreach($val_arr as $key => $val){
if($a[$key] == $b[$key]){
continue;
}
return (($val == 'desc’)?-1:1) * (($a[$key] < $b[$key]) ? -1 : 1);
}
return 0;
}
$cft = array(
array('gold’=>1, 'silver’=>2),
array('gold’=>8, 'silver’=>10),
array('gold’=>8, 'silver’=>8),
array('gold’=>2, 'silver’=>1),
);
uasort($cft, 'multiarray_Compare’);
print_r($cft);

実行結果
Array
(
[0] => Array
(
[gold] => 1
[silver] => 2
)
[3] => Array
(
[gold] => 2
[silver] => 1
)
[1] => Array
(
[gold] => 8
[silver] => 10
)
[2] => Array
(
[gold] => 8
[silver] => 8
)
)

PHP

Posted by arkgame