1

我在 mysql 数据库中有一个包含字符的字符串,并且接下来想执行此操作:

$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 中做到这一点?

4

3 回答 3

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

或在没有第二个循环的情况下改进:

foreach ( $groups as $group ) {
  list($actor, $role) = explode(' as ', trim($group))
  echo $actor . '<br/>';
  echo $role . '<br/>';
  echo '<br/>';
}
于 2013-01-11T13:57:32.387 回答
4
foreach(explode(",", $string) as $value) {
    $parts = explode(" as ", $value);
    echo trim($parts[0])."<br/>".trim($parts[1])."<br/>";        
}
于 2013-01-11T13:58:04.317 回答
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>";
}
于 2013-01-11T14:02:28.867 回答