這將是非常容易的,如果你所有的性質是公開的:
// Test class
class Produit
{
public $id_produit;
public $reference;
// Test data
public function __construct()
{
$this->id_produit = rand(1, 255);
$this->reference = rand(1, 255);
}
}
// Test data array
$array = array(new Produit(), new Produit());
// Notice, you can only use a single character as a delimiter
$delimiter = '|';
if (count($array) > 0) {
// prepare the file
$fp = fopen('test/file.csv', 'w');
// Save header
$header = array_keys((array)$array[0]);
fputcsv($fp, $header, $delimiter);
// Save data
foreach ($array as $element) {
fputcsv($fp, (array)$element, $delimiter);
}
}
但是,正如我所看到的,您的屬性受到保護。這意味着我們無法訪問對象之外的屬性以及循環遍歷它們,或者使用類型轉換來使用(array)。因此,在這種情況下,你必須做出一些改變加時賽對象:
// Test class
class Produit
{
// ...
public function getProperties()
{
return array('id_produit', 'reference');
}
public function toArray()
{
$result = array();
foreach ($this->getProperties() as $property) {
$result[$property] = $this->$property;
}
return $result;
}
}
然後,而不是類型轉換,你可以使用新的方法指定者這樣的:
// Save data
foreach ($array as $element) {
fputcsv($fp, $element->toArray(), $delimiter);
}
也感謝新mehod的GetProperties,我們可以改變頭部得到:
// Save header
fputcsv($fp, $array[0]->getProperties(), $delimiter);
謝謝你,我測試了你的每個例子,並且我得到了相同的結果,這是否正常? (即使我的房產受到保護) – Snow