🙌

2022/02/13に公開

# 結論

array_multisort()関数使えば良いということ。

# 具体例

### 変更前

``````\$shopList = Array
(
[0] => Shop Object
(
[company_name] => Lowson
[attributes:protected] => Array
(
[id] => 1
[code] => 00003
[name] => 長野店
)
)

[1] => Shop Object
(
[company_name] => Seven
[attributes:protected] => Array
(
[id] => ２
[code] => 00001
[name] => 松本店
)
)

[2] => Shop Object
(
[company_name] => Famima
[attributes:protected] => Array
(
[id] => 3
[code] => 00002
[name] => 浜松町店1
)
)
)
``````

こちらを、code順で並び替えたい！という時、

``````foreach (\$shopList as \$k => \$v) {
\$sort[\$k] = \$v['code'];  //ソートする為の配列を用意
}
array_multisort(\$sort, SORT_ASC, \$shopList);
``````

### 変更後

``````\$shopList = Array
(
[0] => Shop Object
(
[company_name] => Seven
[attributes:protected] => Array
(
[id] => ２
[code] => 00001
[name] => 松本店
)
)

[1] => Shop Object
(
[company_name] => Famima
[attributes:protected] => Array
(
[id] => 3
[code] => 00002
[name] => 浜松町店1
)
)
[2] => Shop Object
(
[company_name] => Lowson
[attributes:protected] => Array
(
[id] => 1
[code] => 00003
[name] => 長野店
)
)
)
``````

ちなみにarray_multisortを行う前の\$sortの中身は下記

``````// \$sortの中身
Array
(
[0] => 00003
[1] => 00001
[2] => 00002
)
``````

# 今回使ったarray_multisort()関数

※PHPマニュアル見れば一発ですが

つまり今回は、
\$shopList配列を、\$sort順の変更とともに、同じキーでソートしちゃう」という感じのよう。

ログインするとコメントできます