2017-05-08 21 views
1

我有3爆炸語句:準PHP指數

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

每個explode產生三(3)陣列:

//emails 
Array 
(
    [0] => [email protected] 
    [1] => [email protected] 
    [2] => [email protected] 
    [3] => [email protected] 
) 

//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。例如,我想回顯:

[email protected] Bill Jones 

我該怎麼辦?如果使用適當的語法

回答

2

的foreach可以分配一個鍵和值:

foreach ($emails as $key => $email) { 
    echo $email; 
    echo $firstnames[$key]; 
    echo $lastnames[$key]; 
} 

下一次,參考手冊:http://php.net/manual/en/control-structures.foreach.php,因爲這是在最高層表示。

由於Pyromonk指出的那樣,就是你有索引的數組的情況下非常有用:

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

另外,一個'for'循環可以被用來代替'foreach',因爲它會更有意義在此上下文。 – Pyromonk