1

I'm trying to build a SQL query by looping in PHP using 2 arrays (one of which is array of arrays):

    //build array of arrays using predefined arrays
$regions = array_filter(array($EAPRO, $WCARO, $ROSA, $TACRO, $MENA, $ESARO));

//just a normal array
$regionnames = array('EAPRO', 'WCARO', 'ROSA', 'TACRO', 'MENA', 'ESARO');

$sql = "";

foreach(array_combine($regions, $regionnames) as $region => $regionname)
{
$sql .="UPDATE `database`.`table` SET `region`='$regionname' 
WHERE `countryname` IN (" . implode(",",$region) . ");";
}
echo $sql;

However, debugging this in ideone gives me:

Warning: implode(): Invalid arguments passed on line:
UPDATE `database`.`table` SET `region`='ESARO' WHERE `countryname` IN ();

Which tells me that the array on each loop is not being imploded correctly. Is there something wrong with the way I've defined my array of arrays?

Thanks

7
  • is $region defined ? I don't think so, so try implode(",",$regions) Commented Oct 21, 2012 at 22:48
  • Hmm, $region should be defined by the loop: foreach(array_combine($regions, $regionnames) as $region => $regionname) so on any given loop $region should be set to one of the arrays defined in $regions no? Commented Oct 21, 2012 at 22:52
  • my bad it slipped from my sight ... Commented Oct 21, 2012 at 22:57
  • No probs :) thanks for looking. Commented Oct 21, 2012 at 22:57
  • Hmmm didn't you "flip" in array_combine($regions, $regionnames) the variables ? From the docs it's said php.net/manual/en/function.array-combine.php: array array_combine ( array $keys , array $values ). Try array_combine($regionnames, $regions) Commented Oct 21, 2012 at 23:00

1 Answer 1

1

From the PHP Docs: array_combine ( array $keys , array $values )

So the problem is that the variables are in the wrong places array_combine($regions, $regionnames) (a key can never be an array).

So this should fix the problem:

    //build array of arrays using predefined arrays
$regions = array_filter(array($EAPRO, $WCARO, $ROSA, $TACRO, $MENA, $ESARO));

//just a normal array
$regionnames = array('EAPRO', 'WCARO', 'ROSA', 'TACRO', 'MENA', 'ESARO');

$sql = "";

foreach(array_combine($regionnames, $regions) as $region => $regionname)
{
$sql .="UPDATE `database`.`table` SET `region`='$regionname' 
WHERE `countryname` IN (" . implode(",",$region) . ");";
}
echo $sql;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.