2010-06-17 75 views
2

你好,我有一个数组,看起来像这样,PHP的foreach帮助

Array 
(
    [cfi_title] => Mr 
    [cfi_firstname] => Firstname 
    [cfi_surname] => Lastname 
    [cfi_email] => [email protected] 
    [cfi_subscribe_promotional] => 
    [cfi_tnc] => 
    [friendsName] => Array 
     (
      [0] => Firstname 1 
      [1] => Firstname 2 
      [2] => Firstname 3 
     ) 

    [friendsEmail] => Array 
     (
      [0] => [email protected] 
      [1] => [email protected] 
      [2] => [email protected] 
     ) 

    [submit_form] => Submit 
) 

我的两难困境是我需要从friendsName和friendsEmail阵列中的值保存到数据库中,我知道我可以遍历他们,但我怎样才能发送匹配的数据,例如我需要在同一行数据库上保存[friendsName][0]friendsEmail][0]

我知道我需要使用一个foreach,但我无法弄清楚逻辑。

回答

4
foreach($friendsName as $key=>$val) { 
    $friend = $val; 
    $email = friendsEmail[$key]; 
} 

$count = count($friendsName); 
for($i = 0; $i< $count; ++$i) { 
    $friend = $friendsName[$i]; 
    $email = $friendsEmail[$i]; 
} 

中的每一个上述实施例所使用的假设,即在阵列密钥数据的两个比特

0

完整的解决方案

//Prepare an array for the collected data 
$data = array(); 

//Loop through each of your friends names 
foreach($array['friendsName'] as $key => $value) 
{ 
    //Save the name as part of an associative array, using the key as an identifier 
    $data[$key] = array("name" => $value); 
} 
//Loop through the emails 
foreach($array['friendsEmail'] as $key => $value) 
{ 
    //The array is allready there so just save the email 
    $data[$key]['email'] = $value; 
} 
之间的匹配标识符

$data现在包含您的值配对。