-2

I would like my associative array to have its elements sorted. Currently, my array is like:

Array
(
    [1585] =>  Chicago, Ohio,Dallas, Denver, Detroit, Houston, Las Vegas, So. Calf.
    [1586] =>  Chicago, Ohio, Dallas, Denver, Houston, Las Vegas, So. Calf.
    [1588] =>  The Bay Area, Chicago, Dallas, Detroit, Houston, Las Vegas, Minneapolis
    [1589] =>  Charlotte, Chicago, Ohio, D.C.
    [1590] =>  Orange County, Orlando, Philadelphia, Phoenix, Richmond, San Diego, The Bay Area, Seattle
   )

Whereas I would like this array to be in ascending order like this:

Array
(
    [1585] =>  Chicago, Dallas, Denver, Detroit,Houston, Las Vegas, Ohio, So. Calf.
    [1586] =>  Chicago, Dallas, Denver, Houston, Las Vegas,, Ohio, So. Calf.
    [1588] =>  Chicago, Dallas, Detroit, Houston, Las Vegas, Minneapolis, The Bay Area
    [1589] =>  Charlotte, Chicago, D.C., Ohio
    [1590] =>  Orange County, Orlando,Philadelphia, Phoenix, Richmond,San Diego, Seattle, The Bay Area
   )

Thanks ....

Sled
  • 18,541
  • 27
  • 119
  • 168
vims
  • 29
  • 1
  • 1
  • 2

1 Answers1

2

You need to loop over each element explode on the , to get a list you can actually sort. then you can use a sort function on the list and implode back to , separation. For example:

foreach($arr as $id => $list){
    $listArr = explode(',', $list);
    sort($listArr);
    $arr[$id] = implode(', ', $listArr);
}

This is just a simple example. Depending on the format and consistency of the separation of items in the string you may have to add in some trimming or use preg_split instead of explode but that should give you the basic idea.

prodigitalson
  • 60,050
  • 10
  • 100
  • 114