Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Sort array by field? [duplicate]

Possible Duplicate:
how to sort a multidemensional array by an inner key
How to sort an array of arrays in php?

How can I sort an array like: $array[$i]['title'];

Array structure might be like:

array[0] (   'id' => 321,   'title' => 'Some Title',   'slug' => 'some-title',   'author' => 'Some Author',   'author_slug' => 'some-author' );  array[1] (   'id' => 123,   'title' => 'Another Title',   'slug' => 'another-title',   'author' => 'Another Author',   'author_slug' => 'another-author' ); 

So data is displayed in ASC order based off the title field in the array?

like image 737
Michael Ecklund Avatar asked Apr 03 '12 19:04

Michael Ecklund


People also ask

How to check duplicate in array PHP?

Do you just want to know if there are any duplicates or the quantity and value of said duplicates etc? I only need to know if there are any duplicates. Returning a boolean is perfect. Honestly I think if(count($array) == count(array_unique($array))) is the best you can get.

How to avoid duplicate values in array in PHP?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.

How to remove duplicate value from array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

How to sort multidimensional array in PHP?

Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.


1 Answers

Use usort which is built explicitly for this purpose.

function cmp($a, $b) {     return strcmp($a["title"], $b["title"]); }  usort($array, "cmp"); 
like image 94
meagar Avatar answered Sep 29 '22 09:09

meagar