phparrayspaypalnvp

Paypal NVP TransactionSearch with PHP Array


Hello I am performing a query with the paypal API and my question concerns an array and retrieving values for the key (which is dynamic) I know the query works and credentials are good, as the following array is returned:

array(2) {
["L_TRANSACTIONID0"]=>
string(17) "9FX81733DJ079610B"
["L_TRANSACTIONID1"]=>
string(17) "5E083945JC6368706"
["L_TRANSACTIONID2"]=>
string(17) "7SP75180Y9281954W"
}

I am wanting to break each key out in a foreach loop, but each key is dynamic (notice the count on each key). How can this be accomplished in a foreach loop? Thanks,


Solution

  • I just answered a similar question the other day, so potentially a duplicate. In any case, if this helps someone, here goes:

    function process_response($str)
    {
        $data = array();
        $x = explode("&", $str);
    
        foreach($x as $val)
        {
            $y = explode("=", $val);
    
            preg_match_all('/^([^\d]+)(\d+)/', $y[0], $match);
    
            if (isset($match[1][0]))
            {
                $text = $match[1][0];
                $num = $match[2][0];
    
                $data[$num][$text] = urldecode($y[1]);
            }
            else
            {
                $text = $y[0];
    //          $data[$text] = urldecode($y[1]);
            }
        }
    
        return $data;
    }
    

    Just feed the result from your curl call into this and take the result as a formatted array.

    Note the commented out line, there are some fields that are global, such as version, if you want these, uncomment, but then you may have to adjust some formatting code down stream.

    As an example of how to use this, say you want to feed this into PHPExcel object, you could do so like so:

        $response = your_curl_call($request);
        $data = process_response($response);
    
        $index = 1;
        foreach($data as $row)
        {
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A'.$index, $row['L_TIMESTAMP'])
                ->setCellValue('B'.$index, $row['L_TIMEZONE'])
                ->setCellValue('C'.$index, $row['L_TYPE'])
                ->setCellValue('D'.$index, $row['L_EMAIL'])
                ->setCellValue('E'.$index, $row['L_NAME'])
                ->setCellValue('F'.$index, $row['L_TRANSACTIONID'])
                ->setCellValue('G'.$index, $row['L_STATUS'])
                ->setCellValue('H'.$index, $row['L_AMT'])
                ->setCellValue('I'.$index, $row['L_CURRENCYCODE'])
                ->setCellValue('J'.$index, $row['L_FEEAMT'])
                ->setCellValue('K'.$index, $row['L_NETAMT']);
            $index++;
        }