duanpendan8067 2013-10-06 15:23
浏览 52

如何对字符串数组的子字符串进行排序

I have an array of strings like this:

array
    0 => string 'cheese=french'
    1 => string 'pizza=large&cheese=french'
    2 => string 'cheese=french&pizza=small'
    3 => string 'cheese=italian'

I need to sort each substring (divided by &) in the string in the array alphabettically. So for example: pizza=large&cheese=french should be the other way around: cheese=french&pizza=large, as 'c' comes before 'p'.

I thought i could explode the original array like this:

foreach ($urls as $url)
{
    $exploded_urls[] = explode('&',$url);
}

array
    0 => array
        0 => string 'cheese=french'
    1 => array
        0 => string 'pizza=large'
        1 => string 'cheese=french'
    2 => array
        0 => string 'cheese=french'
        1 => string 'pizza=small'
    3 => array
        0 => string 'cheese=italian'

and then use sort in a foreach loop, like:

foreach($exploded_urls as $url_to_sort)
{
    $sorted_urls[] = sort($url_to_sort);
}

But when I do this, it just returns:

array
    0 => boolean true
    1 => boolean true
    2 => boolean true
    3 => boolean true
    4 => boolean true

up to:

    14 => boolean true

When i do it like this:

foreach($exploded_urls as $url_to_sort)
{
    sort($url_to_sort);
}

I get one of the arrays back, sorted:

array
    0 => string 'cheese=dutch'
    1 => string 'pizza=small'

What's the correct way to go about this?

  • 写回答

2条回答 默认 最新

  • dongwei4103 2013-10-06 15:27
    关注

    sort returns a boolean value (which is practically useless) and does the sort in-place. The code can be as simple as

    // note iteration by reference
    foreach($exploded_urls as &$url_to_sort){
        sort($url_to_sort);
    }
    

    After this loop each element of $exploded_urls will be sorted.

    评论

报告相同问题?