【问题标题】:Insert two associative arrays with foreach loop in codeigniter在codeigniter中使用foreach循环插入两个关联数组
【发布时间】:2021-11-24 17:31:04
【问题描述】:

我正在尝试在 codeigniter 中使用 foreach 循环插入两个数组(关联)

$senti = $this->input->post('field_id'); 
$options = $this->input->post('field');      
           
$i=0;
foreach( $options as $option and $senti as $sen ) 
{
    $insert_option = array
        (
            'form_id' => $token,
            'name' => $this->db->escape_str($option['name']),
            'fillup_id' => $rand,
            'field_id' => $this->db->escape_str($sen['id'])          
        );  
    $this->db->insert('form_value', $insert_option); 
    $i++;
}

但是上面的代码出错了。 另一方面,如果我使用foreach( $options as $option),那么我会得到$option['name'] 的条目,但不会得到$sen['id'] 的条目。
此外,如果这可以通过任何其他循环来完成,我很乐意学习。

【问题讨论】:

  • 您不能随意“扩展”foreach 语法。而且还不清楚您的数组必须从什么结构开始,所以请展示两者的适当示例。

标签: php for-loop post foreach codeigniter-3


【解决方案1】:

不能使用foreach 同时循环两个数组($senti$options)。

你必须找到一种方法来合并这两个数组。下面是while 的示例,但它会跳过最长数组的值。我不知道您使用的数据结构,所以我不知道这是否有问题。

每次迭代 while 都会检查数组中是否存在键 $i。当两个数组中都存在密钥时,它将进行。使用$i++,变量会增加 1,循环可以重新开始。

$senti = $this->input->post('field_id');
$options = $this->input->post('field');

$i = 0;

while(isset($options[$i]) && isset($senti[$i])) {
    $insert_option = array
        (
            'form_id' => $token,
            'name' => $this->db->escape_str($options[$i]['name']),
            'fillup_id' => $rand,
            'field_id' => $this->db->escape_str($senti[$i]['id'])          
        );  
    $this->db->insert('form_value', $insert_option); 
    $i++;
}

【讨论】:

    猜你喜欢
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    相关资源
    最近更新 更多