0

我正在尝试从 mysql 数据中获取数据,并从中创建对象。这里我写了一些代码。我正在从数据库中获取事物的详细信息。现在,对于每个结果,我都希望创建一个最终与数组输出合并的对象。这个$output数组最终输出为 json。

我收到错误:

array_merge(): Argument #2 is not an array

如何在 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;
4

3 回答 3

1

您可以在这里节省一些工作并PDO::FETCH_CLASS用作$fetch_style. 基本上,它允许您指定一个自定义类,您可以使用查询中每一行的匹配返回值填充其属性。注意方法签名中的第一个参数:

公共数组 PDOStatement::fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] )

如文档中的示例 #4 所示PDOStatement::fetchAll()

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

希望这可以帮助 :)

于 2013-11-08T12:55:48.110 回答
1

您可以执行以下操作:

$output = [];
foreach($r as $r1)
{
    $newThing = new Thingy($r1['id']);
    $newThing->getDetails();
    $output[] = $newThing;
}
于 2013-11-08T12:44:36.450 回答
0

我看到了一些可能导致问题的事情。

首先,可能是您的问题的原因是array_merge它只接受 type 的参数array请参阅文档。但是,您可以将类型$newThing转换为数组,或者更简洁地按照其他答案中的建议进行手动附加。

其次,您的方法getDetails()既不返回任何内容,也不是修改对象内容的类方法。它必须是其中之一;现在它运行并且结果不会永久存储在任何地方。既然你已经指出它是一个类方法,那么它应该如下所示:

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
}
于 2013-11-08T12:43:35.493 回答