I have an array that looks like this: Array ( [0] => stdClass Object ( [id] => 23 [parent_id] => 0 [title] => FELA KUTI ) [1] => stdClass Object ( [id] => 24 [parent_id] => 0 [title] => STEPHAN MICUS ) [2] => stdClass Object ( [id] => 25 [parent_id] => 0 [title] => JOHN LEE HOOKER ) ) Code (markup): And I need to sort it alphabetically by the title. How can I do that? Thanks for any help.
<?php $array = array( (object) array( 'id' => 23, 'parent_id' => 0, 'title' => "FELA KUTI" ), (object) array( 'id' => 24, 'parent_id' => 0, 'title' => "STEPHAN MICUS" ), (object) array( 'id' => 25, 'parent_id' => 0, 'title' => "JOHN LEE HOOKER" ) ); $temp = array(); $sorted = array(); foreach($array as $object) $temp[$object->title] = $object; ksort($temp, SORT_STRING); foreach($temp as $title => $object) $sorted[] = $object; print_r($sorted); PHP:
Thanks a million, making the title the index of an array was the part I needed. I'm not very familiar with php syntax, can you tell me the difference between => and ->
Well, when dealing with objects (either accessing an object's property or method) the syntax is $object->property / $object->method($arg1, ...). Off the top of my mind, I think that this is the only occasion when you use -> in PHP. In PHP you may create an array and immediately add some values to it, by writing something like this: $var = array( 'key' => 'value'); echo $var['key']; // Echos 'value' PHP: The foreach control structure may also make use of the symbol =>: foreach (array_expression as $key => $value) statement Code (markup): BTW, here's an alternative solution for your problem, a bit more elegant than the one I've posted above : <?php $array = array( (object) array( 'id' => 23, 'parent_id' => 0, 'title' => "FELA KUTI" ), (object) array( 'id' => 24, 'parent_id' => 0, 'title' => "STEPHAN MICUS" ), (object) array( 'id' => 25, 'parent_id' => 0, 'title' => "JOHN LEE HOOKER" ) ); usort($array, "myComparison"); function myComparison($obj1, $obj2) { return strcasecmp($obj1->title, $obj2->title); } PHP: