1

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

3 Answers 3

3

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

2 Comments

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".
bang on now. I'm using second option.
0

but this does work.

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

Comments

0

How about something like:

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

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.