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

时间:2014-10-15 09:42:49

标签: php mysql arrays

我想使用foreach循环从另一个数组创建一个关联数组。第一个数组只包含一组id来从mysql中检索数据。然后,我想在数组中添加更多元素。

//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"
    )
);

3 个答案:

答案 0 :(得分:1)

在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).")";

答案 1 :(得分:0)

我认为array_push可以解决这个问题:

$first_array = array();    
while($row = $rs->fetch_assoc())
    {   
        $user_data['id'] = $user;
        $user_data['first_name'] = $row['first_name'];
        $user_data['last_name'] = $row['last_name'];
        $user_data['age'] = $row['age'];
        array_push($first_array, $user_data);
    }

答案 2 :(得分:0)

您帖子中的代码似乎是正确的,但$user_data将如下所示:

$user_data = array(
    "111" => array(
        "id" => 111,
        "first_name"=>"Ben",
        "last_name"=>"White",
        "age"=>"43"),
    "222" => array(
        "id" => 222,
        "first_name"=>"Sarah",
        "Benning"=>"37",
        "age"=>"13"),
    "333" => array( ... )
);