0

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.

5
  • can you show the json_encode($arr); output?and is there any errors? Commented May 2, 2016 at 4:53
  • please print_r array before encoding, at least the last portion, from where $latitud_usuario come from and what is the content in it? Commented May 2, 2016 at 4:55
  • i guess it is $obj -> latitud_usuario (instead of $latitud_usuario) Commented May 2, 2016 at 4:56
  • 1
    @FastSnail, it is ok, the problem lies at the value of $latitud_usuario, not at the array...thanks Commented May 2, 2016 at 5:00
  • @mvasco enable errors.so if there is a problem you can see it Commented May 2, 2016 at 5:05

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

don't think this is good answer. in your array you have 'latitud_doctor' => $latitud_usuario and outer the array add the $arr['latitud_doctor']=$latitud_usuario;.
can you tell why 'latitud_doctor' => $latitud_usuario doesn't work ? it should work.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.