Đây là một giải pháp là một mục đích chung hơn một chút. Tôi thực sự đang tìm kiếm một cách để tạo danh sách chuỗi cho các phần chèn số lượng lớn SQL. Mã sẽ trông như thế này:
foreach ($rows as $row) { $string = toDelimitedString($row); // Now append it to a file, add line break, whatever the need may be }Và đây là chức năng hữu ích mà cuối cùng tôi đã thêm vào Takenit của mình:
/** * Convert an array of strings to a delimited string. This function supports CSV as well as SQL output since * the quote character is customisable and the escaping behaviour is the same for CSV and SQL. * * Tests: * echo toDelimitedString([], ',', '\'', true) . "\n"; * echo toDelimitedString(['A'], ',', '\'', true) . "\n"; * echo toDelimitedString(['A', 'B'], ',', '\'', true) . "\n"; * echo toDelimitedString(['A', 'B\'C'], ',', '\'', true) . "\n"; * echo toDelimitedString([], ',', '\'', true) . "\n"; * echo toDelimitedString(['A'], ',', '"', true) . "\n"; * echo toDelimitedString(['A', 'B'], ',', '"', true) . "\n"; * echo toDelimitedString(['A', 'B"C'], ',', '"', true) . "\n"; * * Outputs: * <Empty String> * 'A' * 'A','B' * 'A','B''C' * <Empty String> * "A" * "A","B" * "A","B""C" * * @param array $array A one-dimensional array of string literals * @param string $delimiter The character to separate string parts * @param string $quoteChar The optional quote character to surround strings with * @param bool $escape Flag to indicate whether instances of the quote character should be escaped * @return string */ function toDelimitedString(array $array, string $delimiter = ',', string $quoteChar = '"', bool $escape = true) { // Escape the quote character, since it is somewhat expensive it can be suppressed if ($escape && !empty($quoteChar)) { $array = str_replace($quoteChar, $quoteChar . $quoteChar, $array); } // Put quotes and commas between all the values $values = implode($array, $quoteChar . $delimiter . $quoteChar); // Put first and last quote around the list, but only if it is not empty if (strlen($values) > 0) { $values = $quoteChar . $values . $quoteChar; } return $values; }
Để chuyển đổi một mảng đã cho thành chuỗi CSV (giá trị phân tách bằng dấu phẩy) trong PHP, hãy sử dụng hàm chuỗi Implod (). implode(separator, array) Trả về một chuỗi với các phần tử hoặc array được tham gia bằng cách sử dụng separator được chỉ định. Vì vậy, nếu chúng ta chuyển ký tự dấu phẩy làm đối số cho tham số separator, hàm implode() trả về chuỗi CSV của các phần tử trong array. Trong ví dụ sau, chúng tôi lấy một mảng các số và chuyển đổi các phần tử của mảng này thành chuỗi CSV. Chương trình PHP Đầu ra Trong ví dụ sau, chúng tôi lấy một loạt các chuỗi và chuyển đổi các phần tử của mảng này thành chuỗi CSV.PHP - Chuyển đổi mảng thành chuỗi CSV
Ví dụ
Chuyển đổi mảng số nguyên thành chuỗi CSV
Chuyển đổi mảng chuỗi thành chuỗi CSV
Chương trình PHP
<?php $arr = array("apple", "banana", "cherry"); $output = implode(",", $arr); printf("Output : %s", $output); ?>Đầu ra
Chuyển đổi mảng chuỗi thành chuỗi CSV
Trong ví dụ sau, chúng tôi lấy một loạt các chuỗi và chuyển đổi các phần tử của mảng này thành chuỗi CSV.
PHP có một số chức năng tuyệt vời để phân tích cú pháp và xuất các tệp giá trị phân tách dấu phẩy (CSV), nhưng nó bị thiếu khi trả về dữ liệu đó dưới dạng chuỗi. Chắc chắn, bạn có thể ánh xạ qua mảng với /** * Convert an array of strings to a delimited string. This function supports CSV as well as SQL output since * the quote character is customisable and the escaping behaviour is the same for CSV and SQL. * * Tests: * echo toDelimitedString([], ',', '\'', true) . "\n"; * echo toDelimitedString(['A'], ',', '\'', true) . "\n"; * echo toDelimitedString(['A', 'B'], ',', '\'', true) . "\n"; * echo toDelimitedString(['A', 'B\'C'], ',', '\'', true) . "\n"; * echo toDelimitedString([], ',', '\'', true) . "\n"; * echo toDelimitedString(['A'], ',', '"', true) . "\n"; * echo toDelimitedString(['A', 'B'], ',', '"', true) . "\n"; * echo toDelimitedString(['A', 'B"C'], ',', '"', true) . "\n"; * * Outputs: * <Empty String> * 'A' * 'A','B' * 'A','B''C' * <Empty String> * "A" * "A","B" * "A","B""C" * * @param array $array A one-dimensional array of string literals * @param string $delimiter The character to separate string parts * @param string $quoteChar The optional quote character to surround strings with * @param bool $escape Flag to indicate whether instances of the quote character should be escaped * @return string */ function toDelimitedString(array $array, string $delimiter = ',', string $quoteChar = '"', bool $escape = true) { // Escape the quote character, since it is somewhat expensive it can be suppressed if ($escape && !empty($quoteChar)) { $array = str_replace($quoteChar, $quoteChar . $quoteChar, $array); } // Put quotes and commas between all the values $values = implode($array, $quoteChar . $delimiter . $quoteChar); // Put first and last quote around the list, but only if it is not empty if (strlen($values) > 0) { $values = $quoteChar . $values . $quoteChar; } return $values; } 2, nhưng kết quả của điều đó là gì nếu bạn xử lý thông tin có chứa dấu phẩy trong chính các giá trị? May mắn thay, bạn có thể kết hợp các chức năng tích hợp của PHP với một số cách bao bọc luồng được đặt tốt để lấp đầy các khoảng trống.
Trước hết, các chức năng sau được hỗ trợ bởi PHP ngoài hộp:
- FGETCSV - Tương tự như fgets () ngoại trừ việc fgetcsv () phân tích dòng nó đọc cho các trường ở định dạng CSV và trả về một mảng chứa các trường đọc. - Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.
- FPUTCSV - Định dạng một dòng (được truyền dưới dạng mảng trường) dưới dạng CSV và viết nó (chấm dứt bởi một dòng mới) cho xử lý tệp được chỉ định. - Formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file handle.
- STR_GETCSV - (Php 5.3.0 +) phân tích đầu vào chuỗi cho các trường ở định dạng CSV và trả về một mảng chứa các trường đọc. - (PHP 5.3.0 +) Parses a string input for fields in CSV format and returns an array containing the fields read.
Đoạn mã bên dưới thực hiện một str_putcsv mới, mong đợi một mảng các mảng kết hợp và trả về một chuỗi được định dạng CSV.str_putcsv, which expects an array of associative arrays, and returns a CSV formatted string.
/** * Convert a multi-dimensional, associative array to CSV data * @param array $data the array of data * @return string CSV text */ function str_putcsv($data) { # Generate CSV data from array $fh = fopen('php://temp', 'rw'); # don't create a file, attempt # to use memory instead # write out the headers fputcsv($fh, array_keys(current($data))); # write out the data foreach ( $data as $row ) { fputcsv($fh, $row); } rewind($fh); $csv = stream_get_contents($fh); fclose($fh); return $csv; }Sự kết luận
Chức năng trên đã phát triển từ một năm để viết các tập lệnh xuất dữ liệu để phân phối email. Có các chức năng khác ngoài đó thực hiện chuyển đổi mảng thành CSV, nhưng một số chức năng giới thiệu chi phí bổ sung để sửa các thiếu sót của định dạng CSV. Điều tôi thích là mã trên rõ ràng và súc tích. Bằng cách thuê ngoài chức năng /** * Convert an array of strings to a delimited string. This function supports CSV as well as SQL output since * the quote character is customisable and the escaping behaviour is the same for CSV and SQL. * * Tests: * echo toDelimitedString([], ',', '\'', true) . "\n"; * echo toDelimitedString(['A'], ',', '\'', true) . "\n"; * echo toDelimitedString(['A', 'B'], ',', '\'', true) . "\n"; * echo toDelimitedString(['A', 'B\'C'], ',', '\'', true) . "\n"; * echo toDelimitedString([], ',', '\'', true) . "\n"; * echo toDelimitedString(['A'], ',', '"', true) . "\n"; * echo toDelimitedString(['A', 'B'], ',', '"', true) . "\n"; * echo toDelimitedString(['A', 'B"C'], ',', '"', true) . "\n"; * * Outputs: * <Empty String> * 'A' * 'A','B' * 'A','B''C' * <Empty String> * "A" * "A","B" * "A","B""C" * * @param array $array A one-dimensional array of string literals * @param string $delimiter The character to separate string parts * @param string $quoteChar The optional quote character to surround strings with * @param bool $escape Flag to indicate whether instances of the quote character should be escaped * @return string */ function toDelimitedString(array $array, string $delimiter = ',', string $quoteChar = '"', bool $escape = true) { // Escape the quote character, since it is somewhat expensive it can be suppressed if ($escape && !empty($quoteChar)) { $array = str_replace($quoteChar, $quoteChar . $quoteChar, $array); } // Put quotes and commas between all the values $values = implode($array, $quoteChar . $delimiter . $quoteChar); // Put first and last quote around the list, but only if it is not empty if (strlen($values) > 0) { $values = $quoteChar . $values . $quoteChar; } return $values; } 3 tích hợp của PHP, nó không phải liên quan đến những thứ như /** * Convert an array of strings to a delimited string. This function supports CSV as well as SQL output since * the quote character is customisable and the escaping behaviour is the same for CSV and SQL. * * Tests: * echo toDelimitedString([], ',', '\'', true) . "\n"; * echo toDelimitedString(['A'], ',', '\'', true) . "\n"; * echo toDelimitedString(['A', 'B'], ',', '\'', true) . "\n"; * echo toDelimitedString(['A', 'B\'C'], ',', '\'', true) . "\n"; * echo toDelimitedString([], ',', '\'', true) . "\n"; * echo toDelimitedString(['A'], ',', '"', true) . "\n"; * echo toDelimitedString(['A', 'B'], ',', '"', true) . "\n"; * echo toDelimitedString(['A', 'B"C'], ',', '"', true) . "\n"; * * Outputs: * <Empty String> * 'A' * 'A','B' * 'A','B''C' * <Empty String> * "A" * "A","B" * "A","B""C" * * @param array $array A one-dimensional array of string literals * @param string $delimiter The character to separate string parts * @param string $quoteChar The optional quote character to surround strings with * @param bool $escape Flag to indicate whether instances of the quote character should be escaped * @return string */ function toDelimitedString(array $array, string $delimiter = ',', string $quoteChar = '"', bool $escape = true) { // Escape the quote character, since it is somewhat expensive it can be suppressed if ($escape && !empty($quoteChar)) { $array = str_replace($quoteChar, $quoteChar . $quoteChar, $array); } // Put quotes and commas between all the values $values = implode($array, $quoteChar . $delimiter . $quoteChar); // Put first and last quote around the list, but only if it is not empty if (strlen($values) > 0) { $values = $quoteChar . $values . $quoteChar; } return $values; } 4 để thoát khỏi các giá trị CSV bằng dấu phẩy hoặc báo giá.