追加到数组将替换数组中的所有元素


Appending to array replaces all elements in the array

我正在使用下面的代码从数据库构建一个行数组。

$site = new stdClass();    
$dbh = _vic_commander_db();
    $sth = $dbh->prepare('SELECT name, title, url FROM site ORDER BY siteid');
    $sth->bindColumn(1, $site->name);
    $sth->bindColumn(2, $site->title);
    $sth->bindColumn(4, $site->url);
    $sth->execute();
    $ret = array();
    while ($sth->fetch(PDO::FETCH_BOUND))
    {
        $ret[] = $site;
    }

数组 ($ret[]) 确实会添加到循环的每次迭代中;但是,除了附加表的每一行之外,所有元素都会被追加的最后一个结果替换。所以我有一个数组,其元素数量与表中的行相同,但元素都相同。

任何想法将不胜感激。

示例输出:

    array(3) (
      [0] => stdClass object {
        name => (string) Same Site Name
        title => (string) Same Site Title
        url => (string) samepurl.com
      }
      [1] => stdClass object {
        name => (string) Same Site Name
        title => (string) Same Site Title
        url => (string) samepurl.com
      }
      [2] => stdClass object {
        name => (string) Same Site Name
        title => (string) Same Site Title
        url => (string) samepurl.com
        }
  )

所有数组索引都指向同一个对象$site

您必须按值而不是按引用复制:

$ret[] = clone $site;

见 http://php.net/manual/en/language.oop5.cloning.php

我也想知道为什么你真的需要在这里存储一个对象。

另一个答案有一个不错的解释,但为什么不直接获取对象数组呢?

$sth = $dbh->prepare('SELECT name, title, url FROM site ORDER BY siteid');
$ret = $sth->fetchAll(PDO::FETCH_OBJ);

根据文档(bindColumn()之前的execute())尝试这种方式:

$site = new stdClass();    
$dbh = _vic_commander_db();
    $sth = $dbh->prepare('SELECT name, title, url FROM site ORDER BY siteid');
    $sth->execute();
    $sth->bindColumn(1, $site->name);
    $sth->bindColumn(2, $site->title);
    $sth->bindColumn(4, $site->url); //could you explain why 4?? not 3 ???
    $ret = array();
    while ($sth->fetch(PDO::FETCH_BOUND))
    {
        $ret[] = $site;
    }