为什么我的变量数据在第一个foreach循环后被删除了?

时间:2015-09-06 02:15:41

标签: php codeigniter foreach

我正在使用CodeIgniter在我的数据库中插入记录。一切都运行得很好,除了我似乎无法理解为什么嵌套数组的值在第一个foreach循环后失去其值。

PHP

// $data is all data (array) passed from controller method.
public function create($data)
{
    $my_data = array(
        'name' => $data['name'],
        ....
    );

    if ($this->db->insert('myTable', $my_data)) {
        $insert_id = $this->db->insert_id();

        // $data['mySecondCheckbox'] has value here

        foreach ($first_data['myFirstCheckbox'] as $cb1) {
            $first_data = array(
                'fk_foo_id' => $insert_id,
                'fk_cb_id' => $cb1
            );

            $this->db->insert('mySecondTable', $first_data);
        }

        // $data['mySecondCheckbox'] has no value here

         foreach ($data['mySecondCheckbox'] as $cb2) {
            $second_data = array(
                'fk_foo_id' => $insert_id,
                'fk_cb_id' => $cb2
            );

            $this->db->insert('myThirdTable', $second_data);
        }

        return $insert_id;
    } else {
        return false;
    }

}

谢谢@John!睡在上面后非常明显。当时,我认为$ data特定于每个each范围内。

PHP

// $data is all data (array) passed from controller method.
public function create($data)
{
    $my_data = array(
        'name' => $data['name'],
        ....
    );

    if ($this->db->insert('myTable', $my_data)) {
        $insert_id = $this->db->insert_id();

        // $data['mySecondCheckbox'] has value here

        foreach ($data['myFirstCheckbox'] as $cb1) {
            $first_data = array(
                'fk_foo_id' => $insert_id,
                'fk_cb_id' => $cb1
            );

            $this->db->insert('mySecondTable', $first_data);
        }

        // $data['mySecondCheckbox'] has no value here

         foreach ($second_data['mySecondCheckbox'] as $cb2) {
            $data = array(
                'fk_foo_id' => $insert_id,
                'fk_cb_id' => $cb2
            );

            $this->db->insert('myThirdTable', $second_data);
        }

        return $insert_id;
    } else {
        return false;
    }

}

1 个答案:

答案 0 :(得分:2)

foreach循环中的第一行是重置循环“$ data”中的主题。重命名变量,你应该很好