Search code examples
phpcsvmultidimensional-arrayzend-framework2fgetcsv

cannot get the values from an array


This is a sample array from a csv file upload, which I'm working on

$csvData = array(7) { 
               [" Account Number"]=> string(32) " 1011001562781010" 
               [" Posting Date"]=> string(10) "07/08/2014" 
               [" Value Date"]=> string(10) "07/08/2014"
               [" Description"]=> string(46) "Cash Withdrawal by Cheque173320--TT1421957901"
               [" Debit Amount"]=> string(7) "2000.00"  
               [" Credit Amount"]=> string(0) "" 
               ["Running Balance"]=> string(9) "388392.62" 
            }    

While trying to fetch value using the $csvData ,I get the following error,

Notice: Undefined index: Account Number

This is my code:

foreach ($csvData as $csvRow) {
    $csvData[$key] =$csvRow[$this->_csvColumnAccountNumber];
    if (strtolower($csvRow[$this->_csvColumnAccountNumber]) === $csv_ied_account_number) {
        $CsvValues[$key] = $csvRow[$this->_csvColumnCreditAmount];
        $CsvValues[$key] = $csvRow[$this->_csvColumnDebitAmount];
    }
}

I'm really stuck on this small issue. Please help me solve this as soon as possible.

Thanks in advance.


Solution

  • $csvData is a single dimensional associative array. If you run foreach ($csvData as $csvRow) $csvRow is going to be each value ('1011001562781010', '07/08/2014', and so on) which is not what you want, considering you are trying to access the key which won't be available.

    So the first problem is you don't need a foreach. $csvData[' Account Number'] is what you are after.

    This brings us to the second problem. You have white space in your key. You should run trim() on the data when creating $csvData to get rid of the whitespace. Otherwise, you can do an array_walk and trim the data with an anonymous function:

    array_walk($csvData, function($value, $key) use (&$csvData) {
      unset($csvData[$key]);
      $csvData[trim($key)] = $value;
    });
    

    Above is a pretty complex example for beginners. What this does is goes through every element in $csvData and runs the callback (function) provided. This function will unset the current key and define a new trimmed key. You have to use use (&$csvData) to provide a reference to $csvData in the function's scope.