mvasco mvasco - 7 months ago 31
PHP Question

Passing variable to array

I am passing data base objects to an array.

I need to include another variable to the array. The variable is $latitud_usuario.

Here is the code:

if ($result->num_rows > 0) {
while ($obj = $result->fetch_object()) {
$arr[] = array('nombre_doctor' => $obj->nombre_doctor,'apellido1_doctor' => $obj->apellido1_doctor,'apellido2_doctor' => $obj->apellido2_doctor,'ciudad_doctor' => $obj->ciudad_doctor, 'latitud_doctor' => $latitud_usuario);
}
}
}
echo json_encode($arr);


If I create the array including only fetched objects, the JSON sent is ok, but after including the last array object:

'latitud_doctor' => $latitud_usuario


the JSON is not received as it should.

I guess this last array object expression is wrong.

Any hint is welcome.

Answer

Try this

if ($result->num_rows > 0) {
        while ($obj = $result->fetch_object()) {
            $arr[] = array('nombre_doctor' => $obj->nombre_doctor,'apellido1_doctor' => $obj->apellido1_doctor,'apellido2_doctor' => $obj->apellido2_doctor,'ciudad_doctor' => $obj->ciudad_doctor, 'latitud_doctor' => $latitud_usuario);
           $arr['latitud_doctor']=$latitud_usuario;
        }
    }
}
echo json_encode($arr);