Convert php array to csv string

后端 未结 8 1360
一向
一向 2020-12-10 02:47

I have several method to transform php array to csv string both from stackoverflow and google. But I am in trouble that if I want to store mobile number such as 01727499452,

8条回答
  •  执笔经年
    2020-12-10 03:11

    Here is a solution that is a little more general purpose. I was actually looking for a way to make string lists for SQL bulk inserts. The code would look like this:

    foreach ($rows as $row) {
        $string = toDelimitedString($row);
        // Now append it to a file, add line break, whatever the need may be
    }
    

    And here is the useful function that I ended up adding to my tookit:

    /**
     * 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:
     *  
     *  'A'
     *  'A','B'
     *  'A','B''C'
     *  
     *  "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;
    }
    

提交回复
热议问题