将PHP索引与另一个数组相关联

时间:2017-05-08 00:20:01

标签: php arrays loops for-loop foreach

我有3个爆炸声明:

$emails = explode(',', $row['email']);
$firstnames = explode(',', $row['first_name']);
$lastnames = explode(',', $row['last_name']);

每个explode生成三(3)个数组:

//emails
Array
(
    [0] => test123@example.com
    [1] => lol123@example.com
    [2] => haha@example.com
    [3] => blahblah@example.com
)

//first name
Array
(
    [0] => Bill
    [1] => Jake
    [2] => John
    [3] => Bob
)

//last name
Array
(
    [0] => Jones
    [1] => Smith
    [2] => Johnson
    [3] => Bakers
)

我可以像这样容易得到一个数组:例如:

foreach ($emails as $email) {
    echo $email;
}

这将回复电子邮件。但我想在其中添加$firstname$lastname。例如,我想回应:

test123@example.com Bill Jones

我该怎么做?

1 个答案:

答案 0 :(得分:2)

如果使用适当的语法,foreach可以指定键和值:

for ($i = 0, $n = count($emails); $i < $n; $i++) {
    echo $emails[$i];
    echo $firstnames[$i];
    echo $lastnames[$i];
}

下次,请参阅手册:http://php.net/manual/en/control-structures.foreach.php,因为它显示在最顶层。

正如Pyromonk指出的那样,for在有索引数组的情况下非常有用:

end_date