加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP – 将对象数组导出为CSV

发布时间:2020-12-13 17:46:40 所属栏目:PHP教程 来源:网络整理
导读:我想以CSV格式导出对象数组: array(10) { [0]= object(Produit)#228 (36) { ["id_produit":protected]= string(4) "9999" ["reference":protected]= string(9) "reference1"} [1]= object(Produit)#228 (36) { ["id_produit":protected]= string(4) "8888"
我想以CSV格式导出对象数组:

array(10) {
  [0]=>
  object(Produit)#228 (36) {
    ["id_produit":protected]=> string(4) "9999"
    ["reference":protected]=> string(9) "reference1"
}
  [1]=>
  object(Produit)#228 (36) {
    ["id_produit":protected]=> string(4) "8888"
    ["reference":protected]=> string(9) "reference2"
}
}

在这样的事情:

id_produit | reference | ...
9999 | reference1 | ...
8888 | reference2 | ...

第一行:attribut /列的列表

另一行:Object的attribut的值

True对象的数组示例:http://pastebin.com/8Eyf46pb

我试过这个:Convert array into csv但它对我不起作用.

是否可以这样做(以及如何?)或者我必须在循环中编写每个属性?

解决方法

如果您的所有属性都是公开的,那将非常容易:

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

但正如我所看到的,您的财产受到保护.这意味着我们无法访问对象外的属性以及循环遍历它们或使用(数组)类型转换.所以在这种情况下,您必须对对象进行一些更改:

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

然后你可以使用new方法来代替类型转换,如下所示:

// Save data
foreach ($array as $element) {
    fputcsv($fp,$element->toArray(),$delimiter);
}

还要感谢新的mehod getProperties,我们可以改变标题:

// Save header
fputcsv($fp,$array[0]->getProperties(),$delimiter);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读