开发者

PHP foreach help

Hello I have an array that looks like this,

    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] =&g开发者_开发问答t; Firstname 2
            [2] => Firstname 3
        )

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

    [submit_form] => Submit
)

My dilema is I need to save the values from the friendsName and friendsEmail arrays into a database, I know I can loop through them but how can I send the matching data, for example I need to save [friendsName][0] and friendsEmail][0] on the same row of database?

I know I need to use a foreach but I just cannot figure out the logic.


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

or

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

Each of the above examples are using the assumption that the array key is the matching identifier between the two bits of data


Complete solution

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

$datanow contains your values paired up.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜