2013-01-11 70 views
1

我有一個包含字符和希望做下一個MySQL數據庫之一的字符串:PHP字符串排序

$string = "actor1 as aaa, actor2 as bbb, actor3 as ccc"; 

for (do a loop for 0 to length of the $string) { 
    echo actor1 
    echo aaa 
} 

所以循環進入並打印出每個時間:

actor1 
aaa 

actor2 
bbb 

actor3 
ccc 

如何做到這一點在PHP中?

+1

您最好使用[爆炸](http://php.net/manual/en/function.explode.php)。 – F0G

回答

6

嘗試:

$string = "actor1 as aaa, actor2 as bbb, actor3 as ccc"; 
$groups = explode(',', $string); 

foreach ($groups as $group) { 
    $items = explode(' as ', trim($group)); 
    foreach ($items as $item) { 
    echo $item . '<br/>'; 
    } 
    echo '<br/>'; 
} 

或沒有第二個循環improoved:

foreach ($groups as $group) { 
    list($actor, $role) = explode(' as ', trim($group)) 
    echo $actor . '<br/>'; 
    echo $role . '<br/>'; 
    echo '<br/>'; 
} 
4
foreach(explode(",", $string) as $value) { 
    $parts = explode(" as ", $value); 
    echo trim($parts[0])."<br/>".trim($parts[1])."<br/>";   
} 
+0

謝謝..所有.. :)我嘗試和periklis使用解決方案,並做得很好...謝謝。 – user1949029

+0

好吧,不要忘記標記爲「接受」任何適合您的答案 – periklis

0

注:我假設你有一個查詢,但只是沒有放在適當的查詢字符串,所以我添加了一個典型的mySQL示例。

$query = mysql_query("SELECT actor1 as aaa, actor2 as bbb, actor3 as ccc FROM some_table"); 
$result = mysql_fetch_object($query); 
$numrows = mysql_num_rows($query); 

for ($i = 1; $i <= $numrows; $i++) { 
    echo "actor1 <br>"; 
    echo $result->aaa . "<br>"; 
    echo "actor3 <br>"; 
    echo $result->bbb . "<br>"; 
    echo "actor3 <br>"; 
    echo $result->ccc . "<br>"; 
}