객체

2016-06-06 1 views
0

의 배열에서 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 

어떤 도움을 주시면 감사하겠습니다!

+0

PHP는 객체를 자동으로 배열로 변환 할 수있는 방법을 제공하지 않는다고 생각합니다. 각 개인 "사람"은 대상이므로 사람 배열을 추가하기 전에 각 "사람"을 배열로 변환해야 할 수 있습니다. – apokryfos

+0

'fromArray()'메쏘드는 배열이나 배열의 배열로 동작하지만 객체의 배열에서는 작동하지 않습니다. ([ArrayAccess] (http://www.php.net/manual/en/class.arrayaccess) .php)) –

+0

그래서 Person 클래스는 ArrayAccess를 구현해야합니까? –

답변

0

시도하십시오 : As per oficial documentation, 당신은 돌이 필요 이것이 당신이 ArrayAccess을 구현 한 후

<?php 
date_default_timezone_set('America/Los_Angeles'); 

require_once('PHPExcel.php'); 

$sheet = array(
    array(
     'a1 data', 
     'b1 data', 
     'c1 data', 
     'd1 data', 
    ) 
); 

    $doc = new PHPExcel(); 
    $doc->setActiveSheetIndex(0); 

    $doc->getActiveSheet()->fromArray($sheet, null, 'A1'); 
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 
header('Content-Disposition: attachment;filename="your_name.xls"'); 
header('Cache-Control: max-age=0'); 

    // Do your stuff here 
    $writer = PHPExcel_IOFactory::createWriter($doc, 'Excel5'); 

$writer->save('php://output'); 
?> 
+0

파일에 사용자 지정 개체를 넣지 않으려면 완벽한 Excel 파일을 작성할 수 있습니다. 개체가 배열로 변환된다는 사실을 염두에 두어야합니다 (원본 게시물의 주석 참조). –

0

을 원한 경우

은 알려 주시기 바랍니다 객체 작가로 파일을 저장 먼저 필요 모든 사람을 배열에서 fromArray로 전달합니다.

나는 다음 코드 줄을 테스트하고 일했다 :

는 각 셀 A, B 및 C의 ID, 이름 및 kurzbezeichnung를 붙여 넣이

$i = 1; 
foreach ($persons as $person) { 
    $excelDoc->getActiveSheet()->fromArray((array)$person, null, "A" . $i++); 
} 

이 함께이 부분 $excelDoc->getActiveSheet()->fromArray($persons, null, 'A1'); 교체 사람