의 배열에서 PHPExcel을 만들어 가지고 사람 개체를 DB를 읽어서 생성하는 PersonMapper (PHP 슬림 프레임 워크 3) :객체
<?php
class PersonMapper extends Mapper {
public function getPersons() {
$stmt = $this->db->query("SELECT p.id, p.firstname, p.pastname FROM persons p");
$results = [];
while($row = $stmt->fetch()) {
$results[] = new Person($row);
}
return $results;
}
}
class Person implements ArrayAccess {
protected $id;
protected $firstname;
protected $lastname;
public function __construct(array $data) {
// no id if we're creating
if(isset($data['id'])) { $this->id = $data['id']; }
$this->firstname= $data['firstname'];
$this->lastname= $data['lastname'];
}
public function getId() { return $this->id; }
public function getFirstname() { return $this->firstname; }
public function getLastname() { return $this->lastname; }
public function offsetExists($offset) {
return array_key_exists($offset, $this->asArray());
}
public function offsetGet($offset) {
return $this->offsetExists($offset) ? $this->asArray()[$offset]:NULL;
}
public function offsetSet($offset, $value) {
$this->asArray()[$offset] = $value;
}
public function offsetUnset($offset) {
if ($this->offsetExists($offset)) {
$_array = $this->asArray();
unset($_array[$offset]);
}
}
public function asArray() {
return array(
'id' => $this->id,
'firstname' => $this->firstname,
'kurzbezeichnung' => $this->lastname);
}
}
지금은 사람이 객체의 배열 얻을 수 있어요 :
를$excelDoc = new PHPExcel();
$excelDoc->setActiveSheetIndex(0);
$excelDoc->getActiveSheet()->fromArray($persons, null, 'A1');
$writer = PHPExcel_IOFactory::createWriter($excelDoc, 'Excel2007');
$writer->save("persons.xlsx");
불행하게도, PHPExcel은 하 수 없습니다 :
$mapper = new PersonMapper($this->db);
$persons= $mapper->getPersons();
는 지금은 엑셀 파일로 사람의 목록을 데려 가고 싶다는 이런 종류의 데이터 구조를 조율하십시오 :
Catchable fatal error: Object of class Person could not be converted to
string in /path/to/src/vendor/phpoffice/phpexcel/Classes/
PHPExcel/Cell/DefaultValueBinder.php on line 65
어떤 도움을 주시면 감사하겠습니다!
PHP는 객체를 자동으로 배열로 변환 할 수있는 방법을 제공하지 않는다고 생각합니다. 각 개인 "사람"은 대상이므로 사람 배열을 추가하기 전에 각 "사람"을 배열로 변환해야 할 수 있습니다. – apokryfos
'fromArray()'메쏘드는 배열이나 배열의 배열로 동작하지만 객체의 배열에서는 작동하지 않습니다. ([ArrayAccess] (http://www.php.net/manual/en/class.arrayaccess) .php)) –
그래서 Person 클래스는 ArrayAccess를 구현해야합니까? –