Amboom Amboom - 6 months ago 10
PHP Question

Can only get One item in foreach PHP

I only get one item on my foreach even i have more than one item to loop.
This is my codes:

$sql = "Select vID from info";
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
$dataArray = array();
foreach($users as $user){
$item = $user['vID']
$dataArray['ids'] = $item
}
echo json_encode($dataArray);


This is the data fetch from database:

[
{
"vidID": "1234"
},
{
"vidID": "5678"
}
]


And when i tried to echo my created array, only one item return:

{
"vids": "5678"
}

Answer

That's because you're overriding the id in the array instead of appending.

If you want to append it to the array, replace

$dataArray['ids'] = $item;

With

$dataArray[] = $item;

Or

array_push($dataArray, $item);
Comments