You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
2.4 KiB
90 lines
2.4 KiB
<?php
|
|
|
|
class SqlResultProvider
|
|
{
|
|
/**
|
|
* @var array
|
|
*/
|
|
private $result_items;
|
|
|
|
private $result_items_base;
|
|
|
|
/**
|
|
* @param $result_items array
|
|
*/
|
|
public function __construct($result_items)
|
|
{
|
|
$this->result_items = $result_items;
|
|
}
|
|
|
|
public function assoc($field, $assoc_as_array = false)
|
|
{
|
|
if (is_null($this->result_items_base)) {
|
|
$this->result_items_base = $this->result_items;
|
|
}
|
|
$result_items_assoc = array();
|
|
foreach ($this->result_items_base as $item) {
|
|
if (!isset($item->{$field})) {
|
|
throw new ErrorException('Undefined field. ' . $field);
|
|
}
|
|
if ($assoc_as_array) {
|
|
if (!isset($result_items_assoc[$item->{$field}])) {
|
|
$result_items_assoc[$item->{$field}] = array();
|
|
}
|
|
$result_items_assoc[$item->{$field}][] = $item;
|
|
} else {
|
|
if (isset($result_items_assoc[$item->{$field}])) {
|
|
throw new ErrorException('Field not unique. May be use assoc_as_array. ' . $field);
|
|
}
|
|
$result_items_assoc[$item->{$field}] = $item;
|
|
}
|
|
}
|
|
// Ассоциирование внутри каждого элемента массива
|
|
if ($assoc_as_array) {
|
|
foreach ($result_items_assoc as &$value) {
|
|
$value = new SqlResultProvider($value);
|
|
}
|
|
}
|
|
$this->result_items = $result_items_assoc;
|
|
return $this;
|
|
}
|
|
|
|
public function getKeys()
|
|
{
|
|
return array_keys($this->result_items);
|
|
}
|
|
|
|
public function fetchAll()
|
|
{
|
|
return $this->result_items;
|
|
}
|
|
|
|
/**
|
|
* @param $key
|
|
* @return mixed
|
|
* TODO: метод актуален только после вызова assoc
|
|
*/
|
|
public function fetchKey($key)
|
|
{
|
|
return $this->result_items[$key];
|
|
}
|
|
|
|
/**
|
|
* @param $field
|
|
* @return mixed
|
|
* TODO: метод не актуален после вызова assoc с параметров assoc_as_array = true
|
|
*/
|
|
public function fetchField($field)
|
|
{
|
|
$item = current($this->result_items);
|
|
if ($item) {
|
|
return $item->{$field};
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public function fetch()
|
|
{
|
|
return current($this->result_items);
|
|
}
|
|
}
|