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

使用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条回答 默认 最新

  • douzhi1972 2013-11-08 12:44
    已采纳

    You could do the following:

    $output = [];
    foreach($r as $r1)
    {
        $newThing = new Thingy($r1['id']);
        $newThing->getDetails();
        $output[] = $newThing;
    }
    
    已采纳该答案
    打赏 评论
  • douyi3676 2013-11-08 12:43

    I see a couple things that could potentially be causing problems.

    First, and likely the cause of your issues, is that array_merge only accepts arguments of type array. See the documentation. However, you can either cast the type of $newThing to be an array, or more succinctly just do a manual append as suggested in this other answer.

    Second, your method getDetails() neither returns anything, nor does is it a class method that modifies an object's contents. It needs to be one or the other; right now it runs and the results aren't permanently stored anywhere. Since you've indicated it's a class method, then it should look like this:

    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 ( );
        $this->thingName  = $rslt['name'];                    // Class variable
        $this->thingOwnerId = $rslt['userId'];                // Class variable
        $this->thingDescription = $rslt['thingDescription'];  // Class variable
    
        // 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 ( );
        $this->thingOwnerName = $rslt['firstName']." ".$rslt['lastName']; // Class variable
    }
    
    打赏 评论
  • douwen5066 2013-11-08 12:55

    You could save yourself some work here and use PDO::FETCH_CLASS as the $fetch_style. Basically it allows you to specify a custom class, the properties of which you can populate with matching return values from each row in your query. Note the first argument in the method signature:

    public array PDOStatement::fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] )

    As illustrated in example #4 from the PDOStatement::fetchAll() documentation

    <?php
    class fruit {
        public $name;
        public $colour;
    }
    
    $sth = $dbh->prepare("SELECT name, colour FROM fruit");
    $sth->execute();
    
    $result = $sth->fetchAll(PDO::FETCH_CLASS, "fruit");
    var_dump($result);
    

    Hope this helps :)

    打赏 评论

相关推荐 更多相似问题