将数组转换为 .txt 文件

发布于 2024-09-28 20:18:14 字数 6501 浏览 7 评论 0原文

可能的重复:
将数组转换为 csv

您好,

如何将数组转换为 .txt 文件?

这是我的数组:

Array
(
    [OrderList_RetrieveByContactResult] => Array
        (
            [OrderDetails] => Array
                (
                    [0] => Array
                        (
                            [entityId] => 156456
                            [orderId] => 110631
                            [orderName] => testing2
                            [statusTypeId] => 15656
                            [countryCode] => AU
                            [orderType] => 2
                            [invoiceNumber] => 1001
                            [invoiceDate] => 2010-10-19T00:00:00
                            [userID_AssignedTo] => 245454
                            [shippingAmount] => 8.95
                            [shippingTaxRate] => 0
                            [shippingAttention] => tttesst
                            [shippingInstructions] => this a test
                            [shippingOptionId] => 50161
                            [discountCodeId] => 0
                            [discountRate] => 0
                            [totalOrderAmount] => 143.8
                            [directDebitTypeId] => 0
                            [directDebitDays] => 0
                            [isRecur] => 
                            [nextInvoiceDate] => 0001-01-01T00:00:00
                            [endRecurDate] => 0001-01-01T00:00:00
                            [cycleTypeID] => 1
                            [createDate] => 2010-10-19T05:40:00
                            [lastUpdateDate] => 2010-10-19T05:40:00
                            [deleted] => 
                            [products] => Array
                                (
                                    [Product] => Array
                                        (
                                            [productId] => 455
                                            [productCode] => 
                                            [productDescription] => testtest
                                            [units] => 3
                                            [unitPrice] => 44.95
                                            [unitTaxRate] => 0
                                            [totalProductPrice] => 134.85
                                            [productName] => Skin Support Tablets
                                        )
                                )

                            [addresses] => Array
                                (
                                    [Address] => Array
                                        (
                                            [addressTypeID] => 8
                                            [addressLine1] => Cebu
                                            [city] => City
                                            [zipcode] => 6000
                                            [state] => cebu
                                            [countryCode] => PH
                                        )
                                )

                        )

                    [1] => Array
                        (
                            [entityId] => 315456
                            [orderId] => 321321
                            [orderName] => testing
                            [statusTypeId] => 3213
                            [countryCode] => AU
                            [orderType] => 2
                            [invoiceNumber] => 1002
                            [invoiceDate] => 2010-10-19T00:00:00
                            [userID_AssignedTo] => 11711
                            [shippingAmount] => 8.95
                            [shippingTaxRate] => 0
                            [shippingAttention] => 
                            [shippingInstructions] => 
                            [shippingOptionId] => 50161
                            [discountCodeId] => 0
                            [discountRate] => 0
                            [totalOrderAmount] => 408.45
                            [directDebitTypeId] => 0
                            [directDebitDays] => 0
                            [isRecur] => 
                            [nextInvoiceDate] => 0001-01-01T00:00:00
                            [endRecurDate] => 0001-01-01T00:00:00
                            [cycleTypeID] => 1
                            [createDate] => 2010-10-08T18:40:00
                            [lastUpdateDate] => 2010-10-19T18:36:00
                            [deleted] => 
                            [products] => Array
                                (
                                    [Product] => Array
                                        (
                                            [productId] => 11564
                                            [productCode] => 
                                            [productDescription] => 
                                            [units] => 10
                                            [unitPrice] => 39.95
                                            [unitTaxRate] => 0
                                            [totalProductPrice] => 399.5
                                            [productName] => Acne Clearing Gel
                                        )

                                )

                            [addresses] => Array
                                (
                                    [Address] => Array
                                        (
                                            [addressTypeID] => 8
                                            [addressLine1] => Cebu City
                                            [city] => Cebu
                                            [zipcode] => 6000
                                            [state] => 
                                            [countryCode] => PH
                                        )

                                )

                        )

                )

        )

)

Possible Duplicate:
Convert array into csv

Hi,

How to convert array into .txt file?

This is my array:

Array
(
    [OrderList_RetrieveByContactResult] => Array
        (
            [OrderDetails] => Array
                (
                    [0] => Array
                        (
                            [entityId] => 156456
                            [orderId] => 110631
                            [orderName] => testing2
                            [statusTypeId] => 15656
                            [countryCode] => AU
                            [orderType] => 2
                            [invoiceNumber] => 1001
                            [invoiceDate] => 2010-10-19T00:00:00
                            [userID_AssignedTo] => 245454
                            [shippingAmount] => 8.95
                            [shippingTaxRate] => 0
                            [shippingAttention] => tttesst
                            [shippingInstructions] => this a test
                            [shippingOptionId] => 50161
                            [discountCodeId] => 0
                            [discountRate] => 0
                            [totalOrderAmount] => 143.8
                            [directDebitTypeId] => 0
                            [directDebitDays] => 0
                            [isRecur] => 
                            [nextInvoiceDate] => 0001-01-01T00:00:00
                            [endRecurDate] => 0001-01-01T00:00:00
                            [cycleTypeID] => 1
                            [createDate] => 2010-10-19T05:40:00
                            [lastUpdateDate] => 2010-10-19T05:40:00
                            [deleted] => 
                            [products] => Array
                                (
                                    [Product] => Array
                                        (
                                            [productId] => 455
                                            [productCode] => 
                                            [productDescription] => testtest
                                            [units] => 3
                                            [unitPrice] => 44.95
                                            [unitTaxRate] => 0
                                            [totalProductPrice] => 134.85
                                            [productName] => Skin Support Tablets
                                        )
                                )

                            [addresses] => Array
                                (
                                    [Address] => Array
                                        (
                                            [addressTypeID] => 8
                                            [addressLine1] => Cebu
                                            [city] => City
                                            [zipcode] => 6000
                                            [state] => cebu
                                            [countryCode] => PH
                                        )
                                )

                        )

                    [1] => Array
                        (
                            [entityId] => 315456
                            [orderId] => 321321
                            [orderName] => testing
                            [statusTypeId] => 3213
                            [countryCode] => AU
                            [orderType] => 2
                            [invoiceNumber] => 1002
                            [invoiceDate] => 2010-10-19T00:00:00
                            [userID_AssignedTo] => 11711
                            [shippingAmount] => 8.95
                            [shippingTaxRate] => 0
                            [shippingAttention] => 
                            [shippingInstructions] => 
                            [shippingOptionId] => 50161
                            [discountCodeId] => 0
                            [discountRate] => 0
                            [totalOrderAmount] => 408.45
                            [directDebitTypeId] => 0
                            [directDebitDays] => 0
                            [isRecur] => 
                            [nextInvoiceDate] => 0001-01-01T00:00:00
                            [endRecurDate] => 0001-01-01T00:00:00
                            [cycleTypeID] => 1
                            [createDate] => 2010-10-08T18:40:00
                            [lastUpdateDate] => 2010-10-19T18:36:00
                            [deleted] => 
                            [products] => Array
                                (
                                    [Product] => Array
                                        (
                                            [productId] => 11564
                                            [productCode] => 
                                            [productDescription] => 
                                            [units] => 10
                                            [unitPrice] => 39.95
                                            [unitTaxRate] => 0
                                            [totalProductPrice] => 399.5
                                            [productName] => Acne Clearing Gel
                                        )

                                )

                            [addresses] => Array
                                (
                                    [Address] => Array
                                        (
                                            [addressTypeID] => 8
                                            [addressLine1] => Cebu City
                                            [city] => Cebu
                                            [zipcode] => 6000
                                            [state] => 
                                            [countryCode] => PH
                                        )

                                )

                        )

                )

        )

)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧人哭 2024-10-05 20:18:14

如果您希望它可解析,您可以使用

  • var_export - 输出或返回变量的可解析字符串表示形式

示例

file_put_contents('array.txt', var_export($array, TRUE));

如果您希望它看起来像您的问题中的那样,您可以将 TRUE 作为第二个参数传递给 print_r

file_put_contents('array.txt', print_r($array, TRUE));

EDIT 您在评论中提到您希望将数组转换为 CSV 文件。这个就比较困难了。您的数组是嵌套的,而 CSV 文件基本上是单个暗淡数组,例如,

array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => 'vn');

相当于 CSV 文件,其中第一行是数组键,第二行是值。

k1; k2; ...; kn
v1; v2; ...; vn

单个暗淡数组通常位于另一个数组内,因此您有一个如下所示的集合:

array(
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => 'vn'),
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => 'vn')
);

在这里,您必须首先获取键,然后仅从数组中获取后续行的值,例如

k1; k2; ...; kn
v1; v2; ...; vn
v1; v2; ...; vn

问题是,您的数组嵌套得更深。您会将地址数组放在哪里?唯一可行的方法是遍历数组并仅获取那些包含标量类型的键和值,并对任何嵌套数组进行线性化,例如

array(
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => array( 'skn' => 'svn' ) ),
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => array( 'skn' => 'svn' ) ),
);

必须将其转换为

k1; k2; ...; skn
v1; v2; ...; svn
v1; v2; ...; svn

如果不清楚,这里是一个说明:

< img src="https://i.sstatic.net/ilpiq.png" alt="展平多维数组以在 CSV 文件中使用">

幸运的是,这可以通过迭代器来实现:

$orderDetails = $array['OrderList_RetrieveByContactResult']['OrderDetails'];
foreach( $orderDetails as $key => $details ) {

    $iterator = new RecursiveIteratorIterator(
            new RecursiveArrayIterator($details));

    if($key === 0) {
        $keys = array();
        foreach($iterator as $k => $v) {
            $keys[] = $k;
        }
        echo implode(';', $keys);
    }

    $values = array();
    foreach($iterator as $val) {
        $values[] = $val;
    }
    echo PHP_EOL, implode(';', $values);
}

上面的代码应该输出所描述的格式。有关示例,请参阅 http://www.ideone.com/I70dD

要将其写入文件,您可以将其组装为字符串变量,然后一次性将其全部写入 file_put_contents,或者使用文件指针并逐行写入。如果您不内爆它而是迭代$flattened数组,您也可以使用fputcsv

If you want it to be parseable, you can use

  • var_export — Outputs or returns a parsable string representation of a variable

Example

file_put_contents('array.txt', var_export($array, TRUE));

If you want it to look like in your question, you pass TRUE as the second param to print_r:

file_put_contents('array.txt', print_r($array, TRUE));

EDIT you mentioned in the comments that you want the array to be transformed to a CSV file. This is more difficult. Your array is nested, while a CSV file is basically a single dim array, e.g.

array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => 'vn');

would be equivalent to a CSV file where the first rows is the array keys and the second row the values.

k1; k2; ...; kn
v1; v2; ...; vn

The single dims arrays are usually inside another array, so you have a collection like this:

array(
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => 'vn'),
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => 'vn')
);

Here, you'd have to get the keys first and then fetch only the values from the array for the subsequent lines, e.g.

k1; k2; ...; kn
v1; v2; ...; vn
v1; v2; ...; vn

The problem is, your array is nested even deeper. Where would you put the address array? The only feasible approach would be to go over the array and fetch only those keys and values that contain a scalar type and linearize any nested arrays, e.g.

array(
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => array( 'skn' => 'svn' ) ),
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => array( 'skn' => 'svn' ) ),
);

has to be turned into

k1; k2; ...; skn
v1; v2; ...; svn
v1; v2; ...; svn

In case this isnt clear, here is an illustration what goes where:

Flattening a Multidimensional Array for use in a CSV file

Luckily, this can be achieved with Iterators:

$orderDetails = $array['OrderList_RetrieveByContactResult']['OrderDetails'];
foreach( $orderDetails as $key => $details ) {

    $iterator = new RecursiveIteratorIterator(
            new RecursiveArrayIterator($details));

    if($key === 0) {
        $keys = array();
        foreach($iterator as $k => $v) {
            $keys[] = $k;
        }
        echo implode(';', $keys);
    }

    $values = array();
    foreach($iterator as $val) {
        $values[] = $val;
    }
    echo PHP_EOL, implode(';', $values);
}

The above code should output the described format. See http://www.ideone.com/I70dD for an example.

To write this to a file, you can either assemble this to a string variable and then file_put_contents it all at once or you use a filepointer and write it line by line. If you dont implode it but iterate over the $flattened array, you can also use fputcsv.

傻比既视感 2024-10-05 20:18:14

如果要将变量保存在文本文件中,可以使用 serialize( ) / unserialize()< /a> 的功能:

$data = array(1, 2, 3, '');
$toBeSaved = serialize($data);
file_put_contents('somefile.txt', $toBeSaved);

并恢复它...

$toBeRestored = file_get_contents('somefile.txt');
$data = unserialize($toBeRestored);

If you want to save a variable in a text file, you could use the serialize() / unserialize() functions for that:

$data = array(1, 2, 3, '');
$toBeSaved = serialize($data);
file_put_contents('somefile.txt', $toBeSaved);

And restore it...

$toBeRestored = file_get_contents('somefile.txt');
$data = unserialize($toBeRestored);
2024-10-05 20:18:14

也许您想要的是 fputcsv

Maybe what you want is fputcsv ?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文