分离php数组值

时间:2013-08-22 06:21:39

标签: php html arrays

我在php中有这个数组:

$a[]="Jason White";
$a[]="Jean Black";
$a[]="Billy Brown";

但是我必须在表格中显示这些值,应该是这样的:

+-----------+--------------+
| Firstname | Lastname     |
+-----------+--------------+
| Jason     | White        |
+-----------+--------------+
| Jean      | Black        |
+-----------+--------------+
| Billy     | Brown        |
+-----------+--------------+

有可能这样做吗? 或任何建议来制作这张表?

提前感谢。

4 个答案:

答案 0 :(得分:1)

尝试

echo "<table>";
foreach($a as $name) {
   echo "<tr>";
   $name_arr = explode(" ",$name);
   echo "<td>".$name_arr[0]."</td>";
   echo "<td>".$name_arr[1]."</td>";
   echo "</tr>";
}
echo "</table>";

答案 1 :(得分:0)

用空格展开它并显示它

答案 2 :(得分:0)

是的,这是可能的。此示例假定不必从PHP生成文本“Firstname”和“Lastname”:

<?php
$a = array
(
  'Jason White',
  'Jean Black',
  'Billy Brown',
);
?>

<table>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
  </tr>
<?php
  foreach($a as $val)
  {
    // creates an array from a string 
    // basing on a string character 
    // to be used as an indicator of new array value
    $separate = explode(' ', $val);

    echo '<tr>';

    // to avoid 'undefined index' errors, 
    // loop through the array that was just created.
    foreach($separate as $display)
    {
      echo '<td>'. $display .'</td>';
    }

    echo '</tr>';
  }
?>

</table>

答案 3 :(得分:0)

要将字符串拆分并存储到数组中,请使用PHP函数explode

list($firstName, $lastName) = explode(" ", $var);