PHP – 将对象数组导出为CSV

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP – 将对象数组导出为CSV脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我想以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);

脚本宝典总结

以上是脚本宝典为你收集整理的PHP – 将对象数组导出为CSV全部内容,希望文章能够帮你解决PHP – 将对象数组导出为CSV所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。