Amboom Amboom - 2 years ago 72
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 Source

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;


$dataArray[] = $item;


array_push($dataArray, $item);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download