2015-06-19 43 views
0

我目前正在製作一個網站列出書籍,並且我希望藝術家/作者姓名按字母順序排列。我做了一些與PHP的東西,但它有兩個以上的藝術家/作家時打破... 你能幫助我嗎? phpfiddle鏈接:http://phpfiddle.org/main/code/se6p-wpw3PHP:按字母順序排列字符串

代碼:

<?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'; 
} 
?> 
+0

請在這裏發佈您的代碼,而不只是一個鏈接。 – Barmar

+0

你的代碼在哪裏按字母順序排列藝術家?它看起來像你正在做的是重新'爆炸()'。 – Barmar

+0

只需使用'explode()'在逗號處分割字符串,'sort'按字母順序放入該數組。 – Barmar

回答

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"; 
} 
+0

非常感謝!這正是我想要的!現在我要隱藏在恥辱盒中,因爲答案非常簡單 – LiquidFenrir

+0

echo'$ a,PHP_EOL;' – MECU

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'; 
} 
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