0

I am developing in PHP/MS SQL for getting JSON Response.

Code which I wrote is:

while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {

      $array_res[] = $result;                           // add result to array
      array_push($array_res, array('unidad' => $uni));  // add extra element
      $jsonObj = json_encode($array_res);               // encode JSON 
   }    

echo $jsonObj;

     exit();

This is what I want in result:

[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null,"unidad":1}]

but the result shows me this:

[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null},{"unidad":1}]

1 Answer 1

2

You're fetching an object. Add $uni to $result first and then add to $array_res:

while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {
    $result->unidad = $uni;
    $array_res[] = $result;
}

Also, you probably want the json_encode() after the loop not in the loop:

echo json_encode($array_res);
Sign up to request clarification or add additional context in comments.

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.