【问题标题】:PHP foreach helpPHP foreach 帮助
【发布时间】:2010-06-17 07:54:29
【问题描述】:

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

    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] 和@987654323 @ 在数据库的同一行?

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

【问题讨论】:

    标签: php arrays foreach


    【解决方案1】:
    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];
    }
    

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

    【讨论】:

      【解决方案2】:

      完整的解决方案

      //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 包含配对的值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-20
        • 1970-01-01
        相关资源
        最近更新 更多