PHP:按字母顺序排列字符串

时间:2015-06-19 23:39:40

标签: php string

我目前正在制作一个列出书籍的网站,我希望艺术家/作者的名字按字母顺序排列。我用php制作了一些东西,但是当有超过2位艺术家/作者时,它就会中断... 你能帮助我吗? phpfiddle链接:http://phpfiddle.org/main/code/se6p-wpw3

代码:

<?php
$artist = "John Doe, Ami, lolll";
if (strpos($artist,',') !== false) {
    echo "multiple artists\n";
    $artistchar = str_split($artist);
    $start = 0;
    $artistnum = 0;
    for ($i = 0; $i < count($artistchar); $i = $i + 1) {
        //echo ($i)."\n";
        //echo ($artistchar[$i])."\n";
        if ($artistchar[$i] == ',') {
            echo "implode\n";
            echo ($i)."\n";
            echo ($start)."\n";
            $stop = $i;
            echo ($stop)."\n";
            $artistnum = $artistnum + 1;
            ${'artist'.$artistnum} = implode(array_slice($artistchar, $start, $stop));
            echo (${'artist'.$artistnum})."\n";
            $i = $i + 1;
            $start = $i + 1;
        }
        if ($i == count($artistchar)) {
            echo "implode2\n";
            $artistnum = $artistnum + 1;
            ${'artist'.$artistnum} = implode(array_slice($artistchar, $start, $i));
            echo (${'artist'.$artistnum})."\n";
        }
    }
}
else {
    echo 'only one artist';
}
?>

3 个答案:

答案 0 :(得分:2)

$artist_aray = explode(',', $artist); // Split the input at commas
$artist_array = array_map('trim', $artist_array); // Remove the spaces around the commas
sort($artist_array); // Put them in alphabetical order
foreach ($artist_array as $a) {
    echo "$a\n";
}

答案 1 :(得分:0)

喜欢那个?

$artist = "John Doe, Ami, lolll";
if (strpos($artist,',') !== false) {
    echo "multiple artists\n";
    $artistarray = explode(',', $artist);
    asort($artistarray);
    var_dump($artistarray);
} else {
    echo 'only one artist';
}

答案 2 :(得分:0)

这是你想要做的吗?

$artists = "John Doe, Ami, lolll";
$artists = explode(',', $artist); //slit the string
sort($artists); //reorder parts
$artists = implode(',', $artists); //put the string back together reordered