我有一个与我希望用foreach循环处理的名称相关联的id数组,但是我得到一个错误,上面写着:Undefined offset:n。
我知道这是因为内部数组的长度不同,所以如何解决这个问题呢?我想收集每个名称并在一个函数或循环中查询它们到我的数据库
Array
(
[id_1] => Array
(
[0] => "Jim"
)
[id_2] => Array
(
[0] => "John"
[1] => "Mike"
[2] => "Mary"
)
[id_3] => Array
(
[0] => "Elizabeth"
[1] => "Ashley"
)
)
我要运行的查询是" SELECT * FROM table WHERE id = id
AND name = name
"
使用的foreach循环是:
$count = 0;
foreach ($myArray as $key => $value) {
echo $key . ": " . $value[$count] . '<br>';
$count++;
}
答案 0 :(得分:0)
使用PHP implode连接名称值并在MySQL WHERE子句中使用IN:
// Test array
$myArray = array(
"id_1" => array("Jim"),
"id_2" => array(
"John",
"Mike",
"Mary"
),
"id_3" => array(
"Elizabeth",
"Ashley"
)
);
foreach($myArray as $id => $names) {
// Prepare the MySql statement.
$sqlStr = "SELECT * FROM table WHERE ";
$sqlStr .= "id = '" . $id . "' ";
$sqlStr .= "AND name IN ('" . implode("', '", $names) . "')";
// Execute the query here..
}