php - 使用 foreach 从另一个数组创建关联数组

标签 php mysql arrays

我想使用 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_idid,那么您可以更改$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/

相关文章:

php - Laravel 5 API 授权用于使用 Facebook 进行授权的移动应用程序

php - Symfony cookie 未发送(但在响应 header 中)

mysql - 即使另一个表中不存在记录,如何显示行?

mysql - 添加外键时出错

javascript - 如何将类型数组猴子补丁到 ECMAScript 3 JavaScript 中,特别是 Uint8Array? (Adobe ESTK 中 IDE 必需品)

Ruby:数组的数组到哈希数组

php - 使用PHP将字符串内大括号之间的子字符串提取到数组中

java - 如何在Android中读取HttpResponse?

php - 如果用户选择级联的某个选项,则删除带有文本输入的选择标签

javascript - AngularJS 的 .config()