hector teran
hector teran

Reputation: 379

how to add extra element to array with array_push in PHP?

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}]

Upvotes: 0

Views: 283

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

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

Upvotes: 2

Related Questions