简化数组并另存为CSV

时间:2017-08-09 21:41:07

标签: php arrays clio-api

我有非常复杂的数组:

stdClass Object
(
    [matters] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1050370768
                    [client] => stdClass Object
                        (
                            [id] => 939940280
                            [url] => /api/v2/contacts/939940280
                            [name] => Balter and Son
                        )

                    [display_number] => 00001-Balter and Son
                    [description] => Sueing for pain of having to program
                    [status] => Open
                    [open_date] => 2017-07-26
                    [close_date] =>
                    [pending_date] =>
                    [location] =>
                    [client_reference] => 34241
                    [responsible_attorney] => stdClass Object
                        (
                            [id] => 345011996
                            [url] => /api/v2/users/345011996
                            [name] => jon balter
                            [email] => jbalter@seamlesssolutions.com
                        )

                    [originating_attorney] =>
                    [practice_area] =>
                    [billable] => 1
                    [maildrop_address] => ecd6d7b60+matter1050370768@maildrop.clio.com
                    [created_at] => 2017-07-26T20:46:14+00:00
                    [updated_at] => 2017-07-26T20:46:14+00:00
                    [custom_field_values] => Array
                        (
                        )

                    [billing_method] => hourly
                    [group_id] => 1654280
                    [permission] => stdClass Object
                        (
                            [id] => 1654280
                            [url] => /api/v2/groups/1654280
                            [name] => Firm
                        )

                    [activity_rates] => Array
                        (
                        )

                )

            [1] => stdClass Object
                (
                    [id] => 1050770508
                    [client] => stdClass Object
                        (
                            [id] => 940983330
                            [url] => /api/v2/contacts/940983330
                            [name] => Seamless Solutions
                        )

                    [display_number] => 00002-Seamless Solutions
                    [description] => This is a matter of life and death
                    [status] => Open
                    [open_date] => 2017-08-09
                    [close_date] =>
                    [pending_date] =>
                    [location] =>
                    [client_reference] =>
                    [responsible_attorney] =>
                    [originating_attorney] =>
                    [practice_area] =>
                    [billable] => 1
                    [maildrop_address] => ecd6d7b60+matter1050770508@maildrop.clio.com
                    [created_at] => 2017-08-09T21:37:28+00:00
                    [updated_at] => 2017-08-09T21:37:28+00:00
                    [custom_field_values] => Array
                        (
                        )

                    [billing_method] => hourly
                    [group_id] => 1654280
                    [permission] => stdClass Object
                        (
                            [id] => 1654280
                            [url] => /api/v2/groups/1654280
                            [name] => Firm
                        )

                    [activity_rates] => Array
                        (
                        )

                )

        )

    [records] => 2
    [limit] => 200
    [next_offset] => 1050770508
    [order_dir] => asc
    [total_records] => 2
    [published_at] => 2017-08-09T21:37:38+00:00
)

我只想得到回报 阵列(  [display_number] => 00001-Balter and Son [display_number] => 00002-无缝解决方案 )

然后将其保存为CSV格式 00001,Balter and Son, 00002,Seamless Solutions

任何帮助都会很棒。 我知道必须有一个简单的方法来做到这一点。

有人要求PHP。有点难以放在这里,但我会尝试。它是CLIO法律软件API的一部分。

//Get Matters
$matterarry = matter_numbers ($token);

//get array to just matter numbers
$matternumbers = array(); // initialize the array to be used for the export
foreach($matterarry->matters as $key => $matter) { // loop through all the top level element
    // isolate the display number '00001' from '00001-Balter and Son'
    $displayNumber = explode('-', $matter->display_number);
    $displayNumber = $displayNumber[0];

    // push the element the export array using the display_number as the key
        $matternumbers[$key] = array(
            $displayNumber,  // '00001'
            $matter->client->name   // 'Balter and Son'
        );
    }
Print_r ($matternumbers);

//export to CSV
    $f = fopen('/tmp/matternumbers.csv', 'a');  // open the destination file handler
    fputcsv($f, array('display_number', 'name')); // start by adding the column headers
    // this can also be done by using named keys in your array, 
    // or having the first element be the value of the headers
    // I'm appending manually here for the sake of simplicity
    foreach($matternumbers as $key => $element) {
        fputcsv($f, $element); // append each element to the file
    }
    fclose($f); // don't forget to close the file ;)
function matter_numbers ( $token ) {
//$header = array('Authorization: bearer '.$token);
//print_r ($header);
$header = 'Authorization: bearer '.$token;
echo $header."\r\n";
$ch = curl_init();
//curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_URL, 'https://app.goclio.com/api/v2/matters');
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($ch);

if( !$resp ) {
    die('Error: "' . curl_error( $ch ) . '" - Code: ' . curl_errno( $ch ) );
}

else if ( 200 != curl_getinfo( $ch, CURLINFO_HTTP_CODE ) ) {
    echo "Bad Response Code!";
    echo "\n";
    echo "Response HTTP Status Code : " . curl_getinfo( $ch, CURLINFO_HTTP_CODE );
    echo "\n";
    echo "Response HTTP Body : " . $resp;
}
//print "curl response is:" . $resp;
$resp = json_decode($resp);

//print_r ($resp);
curl_close($ch);

    return $resp;
}

1 个答案:

答案 0 :(得分:1)

我将尝试解决您问题的两个部分(1)简化数组以隔离特定元素,以及(2)将其导出到.csv文件

简化数组

为此,您需要遍历原始对象的所有matters元素,并在具有适当格式的新数组中推送您希望导出的任何值

$exportArray = array(); // initialize the array to be used for the export
foreach($initialObject->matters as $key => $matter) { // loop through all the top level element
    // isolate the display number '00001' from '00001-Balter and Son'
    $displayNumber = explode('-', $matter->display_number);
    $displayNumber = $displayNumber[0];

    // push the element the export array using the display_number as the key
    $exportArray[$key] = array(
        $displayNumber,  // '00001'
        $matter->client->name   // 'Balter and Son'
    );
}

然后你得到一个看起来像这样的数组:

Array [
    0 => Array [
        0 => '00001'
        1 => 'Balter and Son'
    ]
    1 => Array [
        0 => '00002'
        1 => 'Seamless solutions'
    ]
]

或者,您可以使用array_map()而不是循环遍历数组,并获得类似的结果。如果您不熟悉array_map(),可以找到官方文档here

$exportArray = array_map(function($matter) {
    // isolate the display number '00001' from '00001-Balter and Son'
    $displayNumber = explode('-', $matter->display_number);
    $displayNumber = $displayNumber[0];

    return array(
        $displayNumber,
        $matter->client->name
    );
}, $initialObject->matters)

导出为CSV

这部分实际上非常简单,因为PHP具有专门针对此的功能(Official Doc

$f = fopen('/tmp/myFile.csv', 'a')  // open the destination file handler

fputcsv($f, array('display_number', 'name')) // start by adding the column headers
// this can also be done by using named keys in your array, 
// or having the first element be the value of the headers
// I'm appending manually here for the sake of simplicity
foreach($exportArray as $key => $element) {
    fputcsv($f, $element); // append each element to the file
}
fclose($f) // don't forget to close the file ;)

将两者混合在一起

将要导出两次的元素循环播放是单调乏味的,会影响可读性和可维护性。这就是为什么你应该在一个循环中将这些例子混合在一起的原因。

$file = fopen('/tmp/myFile.csv', 'a'); // open the destination file handler
fputcsv($file, array('display_number', 'name')); // add the column headers

foreach($initialObject->matters as $key => $matter) { // loop through all the top level element
    // isolate the display number '00001' from '00001-Balter and Son'
    $displayNumber = explode('-', $matter->display_number);
    $displayNumber = $displayNumber[0];

    // Add the information you need directly in the file
    fputcsv($file, array($displayNumber, $matter->client->name));
}
fclose($file);

为简单起见,我假设您的目标文件为空。如果您在开始使用之前不知道如何确保文件是空的,我建议您查看this这个总结得很好的问题。