読者です 読者をやめる 読者になる 読者になる

by shigemk2

当面は技術的なことしか書かない

多次元配列をソート

PHP

多次元配列をソートする(PHP) - Sometime PHP

たとえば、id cat order order_name という要素がある配列があったとする。
order順に配列をsortしたいときはどうしたらよいのだろうか。

<?php
$arr = array();

$arr['hyaa']['id'] = 5;
$arr['hyaa']['cat'] = 'umihei';
$arr['hyaa']['order'] = 1;
$arr['hyaa']['order_name'] = 'hoge';

$arr['foo']['id'] = 4;
$arr['foo']['cat'] = 'masuo';
$arr['foo']['order'] = 2;
$arr['foo']['order_name'] = 'foo';

$arr['hoge']['id'] = 2;
$arr['hoge']['cat'] = 'namihei';
$arr['hoge']['order'] = 1;
$arr['hoge']['order_name'] = 'hoge';

$arr['amen']['id'] = 3;
$arr['amen']['cat'] = 'andersen';
$arr['amen']['order'] = 1;
$arr['amen']['order_name'] = 'hoge';

$arr['bar']['id'] = 1;
$arr['bar']['cat'] = 'norisuke';
$arr['bar']['order'] = 3;
$arr['bar']['order_name'] = 'bar';

print_r($arr);
Array
(
    [hyaa] => Array
        (
            [id] => 5
            [cat] => umihei
            [order] => 1
            [order_name] => hoge
        )

    [foo] => Array
        (
            [id] => 4
            [cat] => masuo
            [order] => 2
            [order_name] => foo
        )

    [hoge] => Array
        (
            [id] => 2
            [cat] => namihei
            [order] => 1
            [order_name] => hoge
        )

    [amen] => Array
        (
            [id] => 3
            [cat] => andersen
            [order] => 1
            [order_name] => hoge
        )

    [bar] => Array
        (
            [id] => 1
            [cat] => norisuke
            [order] => 3
            [order_name] => bar
        )

)

多次元配列をソートしたいときは、array_multisortを使う。
使い方は以下の通り。

$order = array();
foreach($arr as $key => $row){
  $order[$key] = $row['order'];
}

array_multisort($order, SORT_ASC ,$arr);
print_r($arr);

結果

Array
(
    [hoge] => Array
        (
            [id] => 2
            [cat] => namihei
            [order] => 1
            [order_name] => hoge
        )

    [amen] => Array
        (
            [id] => 3
            [cat] => andersen
            [order] => 1
            [order_name] => hoge
        )

    [hyaa] => Array
        (
            [id] => 5
            [cat] => umihei
            [order] => 1
            [order_name] => hoge
        )

    [foo] => Array
        (
            [id] => 4
            [cat] => masuo
            [order] => 2
            [order_name] => foo
        )

    [bar] => Array
        (
            [id] => 1
            [cat] => norisuke
            [order] => 3
            [order_name] => bar
        )

)

orderでsortしたら、何気にid順にもsortされていた。
藁のようにsortされていた。