0

I have a table that contains id and weight. I want to put both in an associative array.

Right now I've managed to put only the weight in an array:

$weight= array();
$stmt = $dbc->query("SELECT * FROM tbl_weight");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
 $weight[] = $row['weight'];
}

I want to also put the id and make it an associative array.

For example for id = 1 and weight = 50, I want to be able to do something like:

$weight = array("1"=>"50");

How can I do this?

2 Answers 2

3

Just set your key when you append the value. As long as id is unique you shouldn't have any problems

$weight= array();
$stmt = $dbc->query("SELECT * FROM tbl_weight");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $weight[$row['id']] = $row['weight'];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hello, thanks for this. I have another question if you don't mind. Supposed this is the output of the query i.imgur.com/EsSSWFv.png, how can I pair up those id's with the same value? For example in the picture 1 and 3, 2 and 4, 5 and 6? And also 7 and 9, id must not be used twice..
Also, just SELECT id, weight not * unless you later need the other columns.
@FewFlyBy if you have a new question, please post a new question - thanks
1

You'll want to do

$weight[$row['id']] = $row['weight'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.