Как я могу зациклить stdClass в PHP? - PullRequest
0 голосов
/ 13 декабря 2018

Как я могу получить объект stdClass в php?Вот что я сделал ...

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

и когда я распечатываю переменную $ data с помощью var_dump (), я получаю следующее, и я думаю, что все отлично.

    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"

Я пытался зациклить объект $ data с помощью цикла foreach, как это.

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;}}

Класс БД: ..

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

}

** Вопрос в том, ** как мне получить все списки данных по имени и имени пользователя?Большое спасибо.

1 Ответ

0 голосов
/ 13 декабря 2018

Вам придется перебирать _results (или, возможно, даже попробовать results (я не знаю, какую платформу или библиотеку вы используете для связи с базой данных)):

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

РЕДАКТИРОВАТЬ: Поскольку вы определили публичный метод получения results(), который безопасно возвращает вашу переменную private $_results, вы можете сделать следующее:

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

Теперь будет работать.

...