我想使用 foreach 循环从另一个数组创建一个关联数组。第一个数组仅保存一组用于从 mysql 检索数据的 id。然后,我想向数组添加更多元素。
//Array holding all the user_id
$user_id = array("0"=> 111, "1"=>222, "2"=>333);
//The user_id is used to return the data from another table
$sql = "SELECT first_name, last_name, age
FROM user WHERE user_id = ?";
$statement = $DB->link->prepare($sql);
$user_data = array();
foreach($user_id as $user)
{
$statement->bind_param("s", $user);
$statement->execute();
if($rs = $statement->get_result())
{
while($row = $rs->fetch_assoc())
{
//Is it possible to do something like this?
$user_data[$user]['id'] = $user;
$user_data[$user]['first_name'] = $row['first_name'];
$user_data[$user]['last_name'] = $row['last_name'];
$user_data[$user]['age'] = $row['age'];
}
}
}
如何让数组看起来像这里的数组?
$first_array = array(
array(
"user_id" => 111,
"first_name"=>"Ben",
"last_name"=>"White",
"age"=>"43"),
array(
"user_id" => 222,
"first_name"=>"Sarah",
"Benning"=>"37",
"age"=>"13"
)
);
最佳答案
在 foreach 循环中进行数据库查询不是一个好习惯。
您可以使用以下内容:
//Array holding all the user_id
$user_id = array("0"=> 111, "1"=>222, "2"=>333);
//The user_id is used to return the data from another table
$sql = "SELECT user_id, first_name, last_name, age
FROM user WHERE user_id in (".implode(',', $user_id).")";
$statement = $DB->link->prepare($sql);
$statement->execute();
if($rs = $statement->get_result())
{
while($row = $rs->fetch_assoc())
{
//Is it possible to do something like this?
$first_array[] = $row;
}
}
如果您希望字段user_id
为id
,那么您可以更改$sql
var:
$sql = "SELECT user_id as id, first_name, last_name, age
FROM user WHERE user_id in (".implode(',', $user_id).")";
关于php - 使用 foreach 从另一个数组创建关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26379287/