一个foreach中的三个数组?

时间:2013-07-25 04:11:53

标签: php arrays foreach

我正在制作一个小型用户列表"系统,我需要预先三个阵列。 这就是我想要做的事情":

<?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 个答案:

答案 0 :(得分: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>}";
}

答案 1 :(得分: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++;
}

答案 2 :(得分:0)

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

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

答案 3 :(得分: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
}