php str_getcsv array issue

后端 未结 3 827
清歌不尽
清歌不尽 2021-01-05 17:56

I am uploading a csv file and then parsing it using str_getcsv. All works great except that I need a way to cycle through them. Ideally, it\'d be great to have the array com

3条回答
  •  甜味超标
    2021-01-05 18:31

    str_getcsv() expects the string passed as parameter to be one record.
    But since your source is a file anyway the easiest way is probably to use fgetcsv() instead of str_getcsv()

    $data = array();
    $fp = fopen($targetFile, 'rb');
    while(!feof($fp)) {
        $data[] = fgetcsv($fp);
    }
    fclose($fp);
    

    self-contained example:

    prints

    array(3) {
      [0]=>
      array(10) {
        [0]=>
        string(1) "1"
        [1]=>
        string(4) "name"
        [2]=>
        string(7) "address"
        [3]=>
        string(4) "town"
        [4]=>
        string(5) "state"
        [5]=>
        string(3) "zip"
        [6]=>
        string(5) "phone"
        [7]=>
        string(7) "website"
        [8]=>
        string(5) "other"
        [9]=>
        string(5) "other"
      }
      [1]=>
      array(10) {
        [0]=>
        string(1) "2"
        [1]=>
        string(4) "name"
        [2]=>
        string(7) "address"
        [3]=>
        string(4) "town"
        [4]=>
        string(5) "state"
        [5]=>
        string(3) "zip"
        [6]=>
        string(5) "phone"
        [7]=>
        string(7) "website"
        [8]=>
        string(5) "other"
        [9]=>
        string(5) "other"
      }
      [2]=>
      array(10) {
        [0]=>
        string(1) "3"
        [1]=>
        string(4) "name"
        [2]=>
        string(7) "address"
        [3]=>
        string(4) "town"
        [4]=>
        string(5) "state"
        [5]=>
        string(3) "zip"
        [6]=>
        string(5) "phone"
        [7]=>
        string(7) "website"
        [8]=>
        string(5) "other"
        [9]=>
        string(5) "other"
      }
    }
    

    edit2: For using the first element of each record as the key in the result array:

提交回复
热议问题