1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PHP 多重連想配列のソート

Last updated at Posted at 2021-07-11

Every Qiita #9
のんびり独学初学者の毎日投稿チャレンジ 9日目
今回は・・・
PHPでの多重連想配列の並べ替えに関しての備忘録です。

###asort関数を使ってみる
"num"のキーを昇順に揃えていきたいと思います。

$arrs = [
    ["fruit" => "apple" ,"num" => 1 ],
    ["fruit" => "banana" ,"num" => 3 ],
    ["fruit" => "melon" ,"num" => 5 ],
    ["fruit" => "orange" ,"num" => 4 ],
    ["fruit" => "peach" ,"num" => 2 ],
];
asort($arrs);//返り値はbool
foreach ($arrs as $value) {
    echo $value["num"].$value["fruit"];
}

####結果
asortで昇順にしたので見てみましょう。

1apple
3banana
5melon
4orange
2peach

あれ?・・・どうやら配列の最初の値が対象になるみたいです。
"fruit"の値がローマ字昇順でソートされているみたいですね。

###"num"のキーを対象にしたい
配列の最初のキーをnumにしてみます。

$replace_arrs=[];
foreach ($arrs as $key => $value) {
    $replace_arrs[] = array_reverse($arrs[$key]);
}

多重連想配列なので上記でforeach文で1つずつarray_reverse関数を実行します。

####結果

// output
[
    ["num" => 1, "fruit" => "apple"],
    ["num" => 3, "fruit" => "banana"],
    ["num" => 5, "fruit" => "melon"],
    ["num" => 4, "fruit" => "orange"],
    ["num" => 2, "fruit" => "peach"],
]

できました!
あとはasort関数を再度実行します。

###asort関数を使ってみるリターンズ

asort($replace_arrs);

####結果・・・

1apple
2peach
3banana
4orange
5melon

できました!
多重連想配列の場合は、

  1. ソートしたい値を配列の最初に配置
  2. 任意のソート関数を使う

これで行けそうですねー。

//多重連想配列
$arrs = [
    ["fruit" => "apple" ,"num" => 1 ],
    ["fruit" => "banana" ,"num" => 3 ],
    ["fruit" => "melon" ,"num" => 5 ],
    ["fruit" => "orange" ,"num" => 4 ],
    ["fruit" => "peach" ,"num" => 2 ],
];
//numとfruitを入れ替える
$replace_arrs=[];
foreach ($arrs as $key => $value) {
    $replace_arrs[] = array_reverse($arrs[$key]);
}
//numを基準に昇順ソート
asort($replace_arrs);

foreach ($replace_arrs as $value) {
    echo $value["num"].$value["fruit"]."<br>";
}
1
0
4

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
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?