PHP foreach帮助

时间:2010-06-17 07:54:29

标签: php arrays foreach

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

    Array
(
    [cfi_title] => Mr
    [cfi_firstname] => Firstname
    [cfi_surname] => Lastname
    [cfi_email] => test@test.co.uk
    [cfi_subscribe_promotional] => 
    [cfi_tnc] => 
    [friendsName] => Array
        (
            [0] => Firstname 1
            [1] => Firstname 2
            [2] => Firstname 3
        )

    [friendsEmail] => Array
        (
            [0] => email1@address.com
            [1] => email2@address.com
            [2] => email3@address.com
        )

    [submit_form] => Submit
)

我的困境是我需要将来自friendsName和friendsEmail数组的值保存到数据库中,我知道我可以遍历它们但是如何发送匹配的数据,例如我需要保存[friendsName][0]friendsEmail][0]位于同一行数据库中?

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

2 个答案:

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

以上每个例子都假设数组键是两位数据之间的匹配标识符

答案 1 :(得分: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现在包含您配对的值。