mvasco
mvasco

Reputation: 5107

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.

Upvotes: 0

Views: 48

Answers (2)

Webomatik
Webomatik

Reputation: 836

Here's a version that works (using a dummy $obj object):

$obj = (object) array('nombre_doctor'=> 6, 'apellido1_doctor' => 'whatever1', 'apellido2_doctor'  => 'whatever2', 
'ciudad_doctor' => 'Montreal', 'latitud_usuario' => '35463');
$arr[] = array('nombre_doctor' => $obj->nombre_doctor,'apellido1_doctor' => $obj->apellido1_doctor,
'apellido2_doctor' => $obj->apellido2_doctor,'ciudad_doctor' => $obj->ciudad_doctor, 
'latitud_doctor' => $obj->latitud_usuario);

echo json_encode($arr);

Upvotes: 0

sujivasagam
sujivasagam

Reputation: 1769

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

Upvotes: 1

Related Questions