简体   繁体   English

将数组元素添加到sql查询返回的行

[英]add array element to row returned from sql query

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. 我想在将其他值传递给json_encode函数之前将其添加到数组中,但是语法不正确。

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

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;

but this does work. 但这确实有效。

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

How about something like: 怎么样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM