【问题标题】:Appending to array replaces all elements in the array追加到数组替换数组中的所有元素
【发布时间】:2015-03-27 22:11:32
【问题描述】:

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

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

【问题讨论】:

    标签: php arrays replace append


    【解决方案1】:

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

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

    $ret[] = clone $site;
    

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

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

    【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      根据文档(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;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-29
        • 2016-08-23
        • 1970-01-01
        • 2016-11-11
        • 1970-01-01
        • 2022-01-06
        • 2021-12-24
        相关资源
        最近更新 更多