Foreach is returning only one record

Asked

Viewed 1,596 times

3

I have a problem with my code. I have the following code:

<?php
require('class/habeo.class.php');
$Habeo->DuplicateRegister('contatos', array('id'=>'1', 'id'=>'6'));
?>

This class duplicates the records I have in the database. It counts how many elements are in the array and loops to duplicate the id informed. The duplicate class is the following:

<?php
function($de, $condicao){   
    foreach($condicao as $campo=>$value){
        $SQL = mysql_query('INSERT INTO {$de} ({$Columns}) 
                                  SELECT {$Columns} FROM {$de} 
                                  WHERE {$campo}='{$value}');
    }
}
?>

The problem is that it loops with only 1, and there are 2 records in the array.

I visualized that the error is because the array indices are the same name id and so are returning only 1, now when I change the name it returns 2.

  • This array has 2 items array('id'=>'1', 'id'=>'6'); and when I loop with foreach it returns me only the last item. If I change 1 element to another name, it returns 2 items in the loop.

  • 2

    It is normal this behavior, if vc specifies several times the same key in an array, only the last one.

  • how do I solve this problem, because I will duplicate several records and will inform "which" by id then I’ll have to put id=>XXX several times.

  • You will probably have to use another library or function, because anything based on associative array will have the same problem.

  • @Bacco would know some function to use instead of the array() ?

  • 1

    It’s not just changing the array, you have to rethink the whole code of the loop. I would probably use two arrays, this way: novaFuncao( $tabela, Array( campo1, campo2 ...), Array( valor1, valor2...) and a for ( count( ... ) ){ ... }

Show 1 more comment

2 answers

4


As Bacco says, you cannot have more than one key with the same name in an array. But you can call its function several times:

$Habeo->DuplicateRegister('contatos', array('id'=>'1'));
$Habeo->DuplicateRegister('contatos', array('id'=>'6'));

If the Ids are in another array, loop the outside:

$ids = array(1, 6);
foreach($ids as $id) {
    $Habeo->DuplicateRegister('contatos', array('id'=>$id));
}
  • Thanks to you and @Bacco

  • It may be more efficient to do as Bacco suggested (pass an array of fields and another array of values), but this is a quick solution (to write).

3

One option is to use an array:

array( array("id"=>1), array("id"=>2) )

And the loop would look like this:

foreach ($lista as $item) {
    $item["id"];
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.