Reputation: 1886
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
Upvotes: 1
Views: 1380
Reputation: 14921
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;
Upvotes: 1