【问题标题】:How can I loop stdClass in PHP?如何在 PHP 中循环 stdClass?
【发布时间】:2018-12-13 12:43:12
【问题描述】:

如何在 php 中获取 stdClass 对象?这是我所做的......

$data = DB::getInstance()->get('users', array('id', '!=', $user->data()->id));

当我使用 var_dump() 打印出 $data 变量时,我得到了以下信息,我认为它非常好。

    object(DB)#3 (5) {
  ["_pdo":"DB":private]=>
  object(PDO)#4 (0) {
  }
  ["_error":"DB":private]=>
  bool(false)
  ["_results":"DB":private]=>
  array(4) {
    [0]=>
    object(stdClass)#5 (7) {
      ["id"]=>
      string(1) "1"
      ["username"]=>
      string(23) "jonathan@gmail.com"
      ["password"]=>
      string(64) "1adb0639c0f639fb83e1afb113d416080c2106668a18ecc403e91500019c748d"
      ["salt"]=>
      string(32) "_@)V1%G+(@XJ+?(H)+)4-M%C089_#*NE"
      ["name"]=>
      string(15) "Jonathan Living"
      ["joined"]=>
      string(19) "2018-12-07 18:32:26"
      ["type"]=>
      string(1) "1"
    }
    [1]=>
    object(stdClass)#8 (7) {
      ["id"]=>
      string(1) "2"
      ["username"]=>
      string(18) "jonedoe@gmail.com"
      ["password"]=>
      string(64) "c3bcdff85b415bb5759ff284883a764af52781e0283835d98171eb439f7c1f20"
      ["salt"]=>
      string(32) "FZJ3X1&6(C0%)#2@H-0_?!9^8@&U(LV+"
      ["name"]=>
      string(9) "Jone Doe"

我试图用这样的 foreach 循环循环出 $data 对象。

foreach($data as $item) {echo $item['name'];}

foreach($data as $item) {echo $item->name;}

甚至这个,

foreach($data as $items) { foreach($items as $item) { echo $item->name;}}

DB 类是..

<?php class DB{

/**
*Database connection instance
*
*@var $_instance
*/
private static $_instance = null;

/**
*@var $_pdo    Database connection object
*@var $_error  Error for querying
*@var $_result Result set
*@var $_query  Query
*@var $_count  Count
*/
private $_pdo,
        $_error = false,
        $_results,
        $_query,
        $_count = 0;

/**
*PHP Constructor function
*
*@return $this->_pdo connection
*/
private function __construct() {
    try {
        $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
    }catch(PDOException $e) {
        die($e->getMessage());
    }
}

/**
*Singleton pattern that will create only once database connection
*Instantiate object if there already isn't, otherwise return it
*/
public static function getInstance() {
    if(!isset(self::$_instance)) {
        self::$_instance = new DB();
    }
    return self::$_instance;
}

/**
*Execute query and return from the database 
*
*@param string $sql    Query (e.g. 'SELECT * FROM users WHERE username = ')
*@param array  $params Values array that will be binded with the placeholder (e.g. jonathan)
*
*@return ...current object which means if(execute()->success) set $this->_results and $this->_count, otherwise set $this->_error
*/
private function query($sql, $params = array()) {
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)) {
        if(count($params)) {
            $x = 1;
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            } 
        }

        if($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count   = $this->_query->rowCount();
        } else {
            $this->_error = true;
        }
    }
    return $this;
}

/**
*Wrapper between get and delete method and basic query method
*ONLY work for 1 condition
*
*@param string $action 'SELECT *' or 'DELETE'
*@param string $table  users
*@param array  $where  'username = jonathan'
*
*@return  ...current object
*/
public function action($action, $table, $where = array()) {
    if(count($where) === 3) {
        $operators = array('=', '>', '<', '>=', '<=', '!=');

        $field    = $where[0];
        $operator = $where[1];
        $value    = $where[2];

        if(in_array($operator, $operators)) {
            $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";

            if(!$this->query($sql, array($value))->error()) {
                return $this;
            }
        }
    }
    return false;
}

/**
*Get data from database with one condition
*
*@param string $table database table name e.g. users
*@param array  $where condition e.g. username = 'jonathan'
*/
public function get($table, $where) {
    return $this->action('SELECT *', $table, $where); 
}

/**
*Delete data from database with one condition 
*
*@param string $table database table name e.g. users
*@param array  $where condition e.g. username = 'jonathan'
*/
public function delete($table, $where) {
    return $this->action('DELETE', $table, $where);
}

/**
*Insert data into database
*
*@param string $table  table name in database (e.g. users)
*@param array  $fields fields namd with values (e.g. 'username' => 'jonathan')
*
*@return boolean true if insert success, otherwise false
*/
public function insert($table, $fields = array()) {
    $keys = array_keys($fields);
    $placeholder = '';
    $x = 1;

    foreach($keys as $item) {
        $placeholder .= '?';
        if($x < count($keys)) {
            $placeholder .= ', ';
        }
        $x++;
    }
    #INSERT INTO users (`username`, `password`, `salt`) VALUES (?, ?, ?);
    $sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$placeholder});";

    if(!$this->query($sql, $fields)->error()) {
        return true;
    }
    return false;
}

/**
*Update data by id from database
*
*@param string  $table  table name in database (e.g. users)
*@param integer $id     id whose data will be updated (e.g. 3)
*@param array   $fields fields name with values (e.g. 'username' => 'jonathan')
*
*@return boolean true if update success, otherwise false
*/
public function updateById($table, $id, $fields = array()) {
    $set = '';
    $keys = array_keys($fields); // username, password
    $x = 1;

    foreach($fields as $key => $item) {
        $set .= "{$key} = ? ";
        if($x < count($keys)) {
            $set .= ', ';
        }
        $x++;
    }

    #UPDATE users SET username = ?, password = ? WHERE id = 3;
    $sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";

    if(!$this->query($sql, $fields)->error()) {
        return true;
    }
    return false;
}

/**
*Return results in the current object
*
*@return object
*/
public function results() {
    return $this->_results;
}

/**
*Return first result in the current object
*
*@return object
*/
public function first() {
    return $this->results()[0];
}

/**
*Return error in the current object
*
*@return boolean
*/
public function error() {
    return $this->_error;
}

/**
*Return count in the current object
*
*@return integer
*/
public function count() {
    return $this->_count;
}

}

**问题是**如何获取名称和用户名中的所有数据列表?非常感谢。

【问题讨论】:

  • 当你尝试其中任何一个时会发生什么? (诚​​实的问题,我不使用 PDO,所以你的 var_dump() 让我感到困惑,因为它似乎在第二级(在 results[I] 下)最好的实际结果
  • 这是什么框架?
  • 尝试这些时没有任何反应。出现一个空白页。
  • 无框架。只是纯粹的 OOP Php 和 PDO。

标签: php loops stdclass


【解决方案1】:

您将不得不遍历_results(或者甚至可以尝试results(我不知道您使用哪个框架或库进行数据库通信)):

foreach($data->_results as $item) {
    echo $item->username; // first result should be: jonathan@gmail.com
}

编辑:您已经定义了一个公共 getter 方法 results(),它可以安全地返回您的 private $_results 变量,您可以执行以下操作:

foreach($data->results() as $item) {
    echo $item->username; // first result should be: jonathan@gmail.com
}

它现在可以工作了。

【讨论】:

  • 它不起作用。 _result 是 DB 类中的私有变量。我只使用 PDO。
  • 抱歉有点晚了。我刚刚发布了。
  • 在循环中改为$data->results()
  • @omerowitz 非常感谢。现在可以了。谢谢
  • @myxaxa 谢谢。
猜你喜欢
  • 2014-09-19
  • 2016-03-14
  • 2014-06-18
  • 2013-06-23
  • 2015-10-24
  • 1970-01-01
  • 2014-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多