要在插入查询中设置的Implode Array

时间:2014-04-15 07:12:17

标签: php mysql codeigniter

美好的一天!

我的代码将explode the variable value by comma (,)

$tokenize = explode(',', $secondaryRoleCode);
foreach($tokenize as $compare)
{
   $compare = trim($compare);
   $query_secondaryRole = $this->db->query("select ID from role where RoleName like '%".$compare."%';");
   $get_secondaryID = $query_secondaryRole->row_array();
}

之后我只想获得result array with the name of variable的{​​{1}},我将在插入查询中使用如下:

$get_secondaryID

当我print_r:

时,这是$this->db->set('SecondaryRoleID', $get_secondaryID['ID']. ','); $this->db->insert('batch_structure_details'); $id_activity = $this->db->insert_id(); 的结果
$get_secondaryID

我只需要输出如下: Array ( [ID] => 2 ) Array ( [ID] => 3 ) 我的问题是我如何能够结合这些价值。

3, 6, 9是我将用于在3, 6, 9

中插入的值

3 个答案:

答案 0 :(得分:0)

您可以使用简单的for()

$ids = '';
$size = sizeof($get_secondaryID);
for($i=0; $i<=$size-1; $i++)
{
     $ids .= $get_secondaryID[$i]['id'];

     if($i != $size-1)
     {
         $ids .= ',';
     }
}

echo $ids; // will give you something like this 2,34,6,23,11

$this->db->set('SecondaryRoleID', $ids);


OR 您可以使用implode(),但由于这是一个多维数组,因此您必须使用array_map()

$arr = array_map(function($sec){ return $sec['id']; }, $arr);
$ids = implode(',', $arr);
echo $ids; // will give you something like this 2,34,6,23,11

答案 1 :(得分:0)

    I think this following example will help you
    <?php 

    if(isset($_POST['sub'])){
        $demo = array();
        $demo = implode(",",$_POST['dem']);
        var_dump($demo);
    }
    ?>

    <form method="post" action="del.php">
        <input type="text" name="dem[]" />
        <input type="text" name="dem[]" />
        <input type="text" name="dem[]" />
        <input type="submit" name="sub" value=""/>
    </form>

while submitting data[post], getting an array named $demo ,given in example, just separate it, and push it to the query

答案 2 :(得分:0)

您可以使用简单的foreach()

$ids = '';
foreach($get_secondaryID as $sec_id)
{
     if($ids !="")
     {
         $ids .= ",".$sec_id['id'];
     }
     else
     {
         $ids = $sec_id['id'];
     }
}
echo $ids; // will give you something like this 2,34,6,23,11
$this->db->set('SecondaryRoleID', $ids);


OR 您可以使用`implode()

$ids = '';
$arr=[];
foreach($get_secondaryID as $sec_id)
{
         $arr[] = $sec_id['id'];
}
$ids = implode(',', $arr);
echo $ids; // will give you something like this 2,34,6,23,11
$this->db->set('SecondaryRoleID', $ids);