0
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 3 years have passed since last update.

PHP sortについて sort(), asort(), ksort()

Posted at

#各ソートの実施例

例)

<?php 
$arr['aka'] = 'ichigo';
$arr['red']= 'apple';
$arr['yellow'] = 'banana';
$arr['green'] = 'melon';

//var_dump($arr);
//結果
/*
array(4) {
  ["aka"]=>
  string(6) "ichigo"
  ["red"]=>
  string(5) "apple"
  ["yellow"]=>
  string(6) "banana"
  ["green"]=>
  string(5) "melon"
}*/


sort($arr);
// var_dump($arr);//値を元にソート(昇順・キーが数値になる)
//結果
/*
array(4) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(6) "banana"
  [2]=>
  string(6) "ichigo"
  [3]=>
  string(5) "melon"
}
*/

$arr2['aka'] = 'ichigo';
$arr2['red']= 'apple';
$arr2['yellow'] = 'banana';
$arr2['green'] = 'melon';

//var_dump($arr);
//結果
/*
array(4) {
  ["aka"]=>
  string(6) "ichigo"
  ["red"]=>
  string(5) "apple"
  ["yellow"]=>
  string(6) "banana"
  ["green"]=>
  string(5) "melon"
}*/
asort($arr2);//値を元にソート(昇順)
var_dump($arr2);
/*
array(4) {
  ["red"]=>
  string(5) "apple"
  ["yellow"]=>
  string(6) "banana"
  ["aka"]=>
  string(6) "ichigo"
  ["green"]=>
  string(5) "melon"
}
*/

$arr3['aka'] = 'ichigo';
$arr3['red']= 'apple';
$arr3['yellow'] = 'banana';
$arr3['green'] = 'melon';

//var_dump($arr);
//結果
/*
array(4) {
  ["aka"]=>
  string(6) "ichigo"
  ["red"]=>
  string(5) "apple"
  ["yellow"]=>
  string(6) "banana"
  ["green"]=>
  string(5) "melon"
}*/

ksort($arr3);//キーを基準にソート(昇順)
var_dump($arr3);
/*
array(4) {
  ["aka"]=>
  string(6) "ichigo"
  ["green"]=>
  string(5) "melon"
  ["red"]=>
  string(5) "apple"
  ["yellow"]=>
  string(6) "banana"
}
*/
0
0
0

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
0
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?