35

More than 5 years have passed since last update.

posted at

updated at

# 2次元配列の2次元目の配列の値でソートをする

``````
\$array = array(
array(
'id' => 10,
'name' => 'hoge',
),
array(
'id' => 3,
'name' => 'fuga',
),
array(
'id' => 20,
'name' => 'foo',
),
array(
'id' => 1,
'name' => 'bar',
),
);
``````

というような2次元配列があり、2次元目のキー'id'の値でソートをしたいときがちょくちょくある。

そこで、以下の様な関数を作ってみた。

``````function sortArrayByKey( &\$array, \$sortKey, \$sortType = SORT_ASC ) {

\$tmpArray = array();
foreach ( \$array as \$key => \$row ) {
\$tmpArray[\$key] = \$row[\$sortKey];
}
array_multisort( \$tmpArray, \$sortType, \$array );
unset( \$tmpArray );
}
``````

で、以下のように使うと、とてもいい感じになった。

``````\$array = array(
array(
'id' => 10,
'name' => 'hoge',
),
array(
'id' => 3,
'name' => 'fuga',
),
array(
'id' => 20,
'name' => 'foo',
),
array(
'id' => 1,
'name' => 'bar',
),
);

// そのまま出力
print_r( \$array );

// ソート実行
sortArrayByKey( \$array, 'id' );

// もう一度出力
print_r( \$array );
``````
``````Array
(
[0] => Array
(
[id] => 10
[name] => hoge
)

[1] => Array
(
[id] => 3
[name] => fuga
)

[2] => Array
(
[id] => 20
[name] => foo
)

[3] => Array
(
[id] => 1
[name] => bar
)

)
Array
(
[0] => Array
(
[id] => 1
[name] => bar
)

[1] => Array
(
[id] => 3
[name] => fuga
)

[2] => Array
(
[id] => 10
[name] => hoge
)

[3] => Array
(
[id] => 20
[name] => foo
)

)
``````

Register as a new user and use Qiita more conveniently

1. You get articles that match your needs
2. You can efficiently read back useful information
What you can do with signing up
35