Amboom
Amboom

Reputation: 156

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"
}

Upvotes: 1

Views: 108

Answers (1)

Chin Leung
Chin Leung

Reputation: 14921

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

Upvotes: 3

Related Questions