siempreCurioso siempreCurioso - 1 year ago 46
jQuery Question

json_enode() returns array of objects for singular values

The below code has only array like ["a","b","c"] but returns [Object,Object,Object]. The result of which I need to use nested $each loop in ajax success function. Is there any better way to do it?

if($_GET['semValue'])
{
$sem_value = $_GET['semValue'];
try
{

$stmt = $dbConn->prepare("SELECT Semester FROM CourseInfo");
$semArray = array();
if ($stmt->execute())
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$semArray[] = $row;
}
}
echo json_encode($semArray);
exit();

}
catch(PDOException $e)
{
echo 'Exception -> ';
var_dump($e->getMessage());
}

Answer Source

You're inserting entire row in main array so it will return multidimensional array instead of array of string.

To get the array of string replace the following lines.

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) 
{
     $semArray[] = $row["Semester"];
}