doumen9709
2013-11-08 12:38
浏览 122
已采纳

使用for循环在PHP中创建一个对象数组

I am trying to get data from mysql data, create objects from it. Here I have written some code. I am getting thing's details from a database. Now for each result I want an object to be created which is finally merged with an array output. This $output array is finally outputted as json.

I am getting error :

array_merge(): Argument #2 is not an array

How to create arrays of objects in PHP ?

public function getDetails()    //This is a class function
{
    $query = "SELECT * FROM `thing` WHERE `id` = :thingId";
    $stmt = $dbh->prepare ( $query );
    $stmt->bindParam ( ":thingId" , $_GET['thingId']  );
    $stmt->execute ( );
    $rslt  =  $stmt->fetch ( );
    $thingName  = $rslt['name'];
    $thingOwnerId = $rslt['userId'];
    $thingDescription = $rslt['thingDescription'];

    // Getting the thing owner details
    $query = "SELECT * from `user` WHERE ( `id` = :id ) ";    
    $stmt = $dbh->prepare( $query );
    $stmt->bindParam ( ":id" , $thingOwnerId );
    $stmt->execute(  );
    $rslt = $stmt->fetch ( );
    $thingOwnerName = $rslt['firstName']." ".$rslt['lastName'];
}

$query = "SELECT * FROM `things` ; ";
$s = $dbh->prepare($query);
$s->execute();
$r = $s->fetchAll();
foreach($r as $r1)
{
    $newThing = new Thingy($r1['id']);
    $newThing->getDetails();
    $output =  array_merge($output,$newThing);
}

$output2 = json_encode($output);
header('content-type: application/json');
echo $output2;

图片转代码服务由CSDN问答提供 功能建议

我正在尝试从mysql数据中获取数据,从中创建对象。 在这里,我写了一些代码。 我从数据库中获取了东西的细节。 现在,对于每个结果,我想要创建一个最终与数组输出合并的对象。 这个 $ output 数组最终输出为json。

我收到错误:

array_merge() :参数#2不是数组

如何在PHP中创建对象数组?

  public function getDetails(  )//这是一个类函数
 {
 $ query =“SELECT * FROM`thing` WHERE`id` =:thingId”; 
 $ stmt = $ dbh-> prepare($ query); 
  $ stmt-> bindParam(“:thingId”,$ _GET ['thingId']); 
 $ stmt-> execute(); 
 $ rslt = $ stmt-> fetch(); 
 $ thingName  = $ rslt ['name']; 
 $ thingOwnerId = $ rslt ['userId']; 
 $ thingDescription = $ rslt ['thingDescription']; 
 
 //获取东西所有者详细信息
 $ query  =“SELECT * from`user` WHERE(`id` =:id)”;  
 $ stmt = $ dbh-> prepare($ query); 
 $ stmt-> bindParam(“:id”,$ thingOwnerId); 
 $ stmt-> execute(); 
 $ rslt =  $ stmt-> fetch(); 
 $ thingOwnerName = $ rslt ['firstName']。“”。$ rslt ['lastName']; 
} 
 
 $ query =“SELECT * FROM`thing`  ;“; 
 $ s = $ dbh-> prepare($ query); 
 $ s-> execute(); 
 $ r = $ s-> fetchAll(); 
foreach($ r as  $ r1)
 {
 $ newThing = new Thingy($ r1 ['id']); 
 $ newThing-> getDetails(); 
 $ output = array_merge($ output,$ newThing); 
  } 
 
 $ output2 = json_encode($ output); 
header('content-type:application / json'); 
echo $ output2; 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题