1

我正在研究一个小型“用户列表”系统,我需要为三个数组。这是我“想要做的”:

<?php
$users = array("user1", "user2");
$descriptions = array("user1 description", "user2 description");
$socials = array("skype: user1", "skype: user2");
foreach ($users as $user && $description as $description && $socials as $social) {
echo "<tr><td style=\"width:60px\"><img width=\"50\" height=\"50\" alt=\"{$user}'s profile picture\" src=\"blog/users/{$user}/avatar.png\"><br/>{$user}</td><td style=\"width:70%\">{$descriptions}</td><td style=\"text-align:left\">{$social}</td></tr>}";}
?>

我怎样才能使这项工作?

4

4 回答 4

3

您可以将array_map与 null 第一个参数一起使用,您可以从这三个参数构建一个多维数组,然后使用 foreach 遍历它

$combined = array_map(null, $users, $descriptions, $socials);
foreach ($combined as $user) {
    $username = $user[0];
    $description = $user[1];
    $social = $user[2];
    echo "<tr><td style=\"width:60px\"><img width=\"50\" height=\"50\" alt=\"{$username}'s profile picture\" src=\"blog/users/{$username}/avatar.png\"><br/>{$username}</td><td style=\"width:70%\">{$description}</td><td style=\"text-align:left\">{$social}</td></tr>}";
}
于 2013-07-25T04:17:19.517 回答
1
$users = array("user1", "user2"); 
$descriptions = array("user1 description", "user2 description"); 
$socials = array("skype: user1", "skype: user2"); $i = 0; 
foreach ($users as $user)
{ 
  $html .= "{$user}{$descriptions[$i]}{$socials[$i]}"; 
  $i++;
}
于 2013-07-25T05:41:39.220 回答
0

您可以使用keyinforeach来调用另一个数组(假设它们匹配):

<?php
$users = array("user1", "user2");
$descriptions = array("user1 description", "user2 description");
$socials = array("skype: user1", "skype: user2");
foreach ($users as $key=>$user) {
echo "<tr><td style=\"width:60px\"><img width=\"50\" height=\"50\" alt=\"{$user}'s profile picture\" src=\"blog/users/{$user}/avatar.png\"><br/>{$user}</td><td style=\"width:70%\">{$descriptions[$key]}</td><td style=\"text-align:left\">{$social[$key]}</td></tr>}";}

另外,不建议在一个echo. 我更喜欢将heredoc所有内容“分开”的方法,以便您可以直观地阅读(并进行更改):

foreach ($users as $key=>$user) {
    echo <<<EOD

    <tr>
        <td style="width:60px"><img width="50" height="50" alt="{$user}'s profile picture" src="blog/users/{$user}/avatar.png"><br>{$user}</td>
        <td style="width:70%">{$descriptions[$key]}</td>
        <td style="text-align:left">{$social[$key]}</td>
    </tr>
EOD;
}
于 2013-07-25T04:15:09.660 回答
0

运行一个 for 循环,一次遍历所有 3 个数组。

for ($i = 0; $i < count($users); $i++)
{
    echo $users[$i].'<br />'; //get location $i of array $users
    echo $descriptions[$i].'<br />'; //get location $i of array $descriptions
    echo $socials[$i].'<br />'; //get location $i of array $socials
}
于 2013-07-25T04:18:42.803 回答