0

I have some problem with sort data array by alphabetical

I've read about the sort in the following link PHP 5 Sorting Arrays

And here I have tried some functions and not as expected, look at the following picture Click Here

But my question is what if i want to sort array from second key then sort alphabetically

Sample Array

[0] => Array (
    [id] => 46759
    [nama] => Albino
)
[1] => Array (
    [id] => 46772
    [nama] => Saputra
)
[2] => Array (
    [id] => 46710
    [nama] => Soni Putra
)
[3] => Array (
    [id] => 46760
    [nama] => Abian
)

And i want result sort by "nama" so result of that's array like this

- Abian
- Albino
- Saputra
- Soni Putra

I try using sort() or asort() with many array but the letter "A" is still some that are not sorted according to the order of the letters, is there any other solution to solve this problem ?

UPDATE

I have solution from this Link, thanks for answering my question.

Ivan Juliant
  • 97
  • 1
  • 14
  • You can start with http://php.net/manual/en/function.usort.php to build a custom sorting callback, within your function you can interrogate the 'nama' array key and perform a strcmp or attempt to sort using http://php.net/manual/en/function.array-multisort.php – Scuzzy Jul 27 '18 at 08:30
  • the answer can be find here https://stackoverflow.com/questions/16306416/sort-php-multi-dimensional-array-based-on-key – azizsagi Jul 27 '18 at 08:32
  • @azizsagi i try your link and work but why just first word can be sort ? – Ivan Juliant Jul 27 '18 at 08:48
  • Possible duplicate of [How can I sort arrays and data in PHP?](https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – user3942918 Jul 27 '18 at 08:50

1 Answers1

2

Example of a custom sorting callback using usort() and strcmp().

This is the cleanest and simplest way to perform this type of sorting.

note: strnatcmp() is available too if you need "natural sorting"

$array = array(
  array(
    'id' => 46759,
    'nama' => 'Albino'
  ),
  array(
    'id' => 46772,
    'nama' => 'Saputra'
  ),
  array(
    'id' => 46710,
    'nama' => 'Soni Putra'
  ),
  array(
    'id' => 46760,
    'nama' => 'Abian'
  )
);

usort( $array, function( $a, $b ){
  return strcmp( $a['nama'], $b['nama'] );
});

If you want re-usable

function sortByKey( &$array, $key ){
  usort( $array, function( $a, $b ) use ( $key ){
    return strcmp( $a[ $key ], $b[ $key ] );
  });
}

sortByKey( $array, 'nama' );
Scuzzy
  • 12,186
  • 1
  • 46
  • 46