views:

47

answers:

2
+2  Q: 

PHP foreach help

Hello I have an array that looks like this,

    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
)

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.

+4  A: 
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

Lizard
A: 

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.

Kristoffer S Hansen