Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

orderring the elements of an array

Status
Not open for further replies.

breaststroke

Programmer
Apr 10, 2011
39
ES
Hello!

I am not sure about what (and how) function to use to order the elements of an array.
I have an array whose elements are strings and these are like sentences. I would like to order it by alphabetical order of the first word after the first space.

For instance, if this is the array:

$thisarray= ("strangers in the night", "i cant think", "a problem to be solved"):
it would become the following, afterwards:
$thisarray= ("i cant think", "strangers in the night", "a problem to be solved");

because "cant" comes before "in" which comes before "problem" in an alphabetical order.

Any hint, please? I would appreciate it!

enjoy practicing languages at:
 
that sounds most illogical.

the way i guess i'd approach this is to loop every element and split the string into an array. the extract the second word in each to a new array.
then sort the new array, keeping the key order.
the reassemble the original array in the order designated by the new array.

or you could build an ordering comparator, but i suspect using the compiled functions will be quicker.
 
Yes, it makes sense. I can make a new array stracting the first term from its elements and the use array_search to find out what the position of each element is, in the new array, and order the former according to it.
Thank you!

enjoy practicing languages at:
 
Yes, it makes sense. I can make a new array stracting the first term from its elements, order it and then use array_search to find out what the position of each element is, in the new array, and order the former according to it.
Thank you!

enjoy practicing languages at:
 
not that complex. you don't need to use expensive operations like array_search

Code:
<?php
$array = Array("strangers in the night", "i cant think", "a problem to be solved");
$tempArray = $outputArray = array();
foreach($array as $item) list($ignore, $bitsArray[]) = explode(' ', $item);
asort($bitsArray);
foreach(array_keys($bitsArray) as $item) $outputArray[] = $array[$item];
print_r($outputArray);

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top