Thursday 30 August 2018

Create an associative array from another array with foreach

I would like to create an associative array from another array using a foreach loop. The first array only hold a set of id to retrieve data from mysql. Then, I would like to add more elements to the array.

//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'];
        }
    }
}

How can I get the array to look like this array here?
$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"
    )
);


I think an array_push might do the trick:
$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);
    }

0 comments:

Post a Comment