views:

68

answers:

3

I want to add an additional value into an array before passing it to json_encode function, but I can't get the syntax right.

 $result = db_query($query);

  // $row is a database query result resource
  while ($row = db_fetch_object($result)) {

  $stack[]  = $row; 
                // I am trying to 'inject' array element here
  $stack[]['x']  = "test";  
 }

echo json_encode($stack); 
+2  A: 

If it's an array you can directly add a value:

$row['x'] = 'test';
$stack[] = $row;

if it's an object you can add another property:

$row->x = 'test';
$stack[] = $row;

if you want to keep the object and the extra value separated:

$data = array($row, 'x' => 'test');
$stack[] = $data;
kemp
that was my first inclination, but it gives "Cannot use object of type stdClass as array in" In mySQL the value returned would be an associative array of strings that corresponds to the fetched row.In Drupal's database abstraction layer, the value returned is a "database query result resource".
bert
Edited my answer.
kemp
bang on now. I'm using second option.
bert
A: 

but this does work.

$stack[]  = $row;       
$row->x = 'test';
bert
A: 

How about something like:

$row['x'] = 'test';
$stack = $row;
dscher