2010-10-18 46 views
0

当您将PDT交易ID发回贝宝时,您将返回交易数据列表。它在第一行有SUCCESS,然后是键=值对列表。每行一对。例如:PHP:如何快速将密钥=值文件分割为关联数组

SUCCESS 
[email protected] 
charset=windows-1252 
custom= 
first_name=Alice 
handling_amount=0.00 
invoice=NN0005 
item_name=Bear 
item_number=BEAR05 
last_name=Foobar 
mc_currency=SEK 
mc_fee=13.00 
mc_gross=250.00 
[email protected] 
payer_id=UC9DXVX7GRSTN 
payer_status=unverified 
payment_date=09:08:06 Oct 18, 2010 PDT 
payment_fee= 
payment_gross= 
payment_status=Completed 
payment_type=instant 
protection_eligibility=Ineligible 
quantity=1 
receipt_id=2479-2605-1192-2880 
[email protected] 
receiver_id=8Y670ENTB8BY6 
residence_country=NO 
shipping=0.00 
tax=0.00 
transaction_subject=Bear 
txn_id=1PH815997L239283J 
txn_type=web_accept 

什么是检查第一行是否等于SUCCESS然后将其转换为关联数组的好方法,快速而干净的方法?我能够做到这一点,但它很有用,但我很好奇,如果有更好或更干净的做法,导致我最终结果并不总是那么好。请注意,某些键也没有任何值。

所以,我想直到结束本质是:

array(
    'business' => '[email protected]', 
    'charset' => 'windows-1252', 
    'custom' => NULL, 
    'first_name' => Alice, 

    // And so on 

); 

的顺序并不重要。

更新:感谢您的伟大建议!现在测试它们。顺便把字符串拆分成不同的行也是我的问题的一部分。忘了说明一下。看到有些人已经考虑到了这一点,有些则没有。它可以产生影响,因为某些方法需要首先分割成线条,然后再分割成两条线,而另一些方法则可以将整个东西整体分割。

更新:我还应该提到,有空的结束为NULL将是一个奖金,但可能不是必需的。他们在我的版本中也没有这样做,这并不重要。


基准测试结果

得到了好奇,我应该选择这里什么,所以我为基准我应该怎么做不同的部分。我自己有各种各样的想法,也从这里和其他地方得到了一些。当我找到了我能够管理的最快速度时,我创建了一个基准并针对迄今为止的所有答案进行了测试。对于跳过分裂或成功检查的人,我添加了一个explodestrpos相应的检查。我还为所有的解决方案添加了urldecode,除了@dynamism,他们很好地解决了这个问题。不管怎么说,这里的结果:

Benchmark results

基准是使用codebench 模块运行。下面是基准代码:

<?php defined('SYSPATH') or die('No direct script access.'); 

/** 
* Test various methods of checking for SUCCESS 
* 
* @package PayPal 
* @category PDT 
* @author Torleif Berger 
*/ 
class Bench_ProcessPDT extends Codebench 
{ 
    public $description = 'Various ways of checking that a string starts with SUCCESS'; 

    public $loops = 100000; 


    public function bench_mine($subject) 
    { 
     if(strpos($subject, 'SUCCESS') === 0) 
     { 
      $subject = urldecode(substr($subject, 7)); 
      preg_match_all('/^([^=]++)=(.*+)/m', $subject, $result, PREG_PATTERN_ORDER); 
      $result = array_combine($result[1], $result[2]); 

      return array(count($result), array_shift($result), array_shift($result)); 
     } 
     return FALSE; 
    } 

    // http://stackoverflow.com/questions/3964219/3964308#3964308 
    public function bench_dynamism_substr($subject) 
    { 
     if(substr($subject, 0, 7) == 'SUCCESS') 
     { 
      $subject = substr_replace($subject, '', 0, 7); 
      $subject = str_replace(array("\n", "\r", "\r\n"), '&', $subject); 
      parse_str($subject, $result); 

      return array(count($result), array_shift($result), array_shift($result)); 
     } 
     return FALSE; 
    } 

    // http://stackoverflow.com/questions/3964219/3964308#3964308 
    public function bench_dynamism_strpos($subject) 
    { 
     if(strpos($subject, 'SUCCESS') === 0) 
     { 
      $subject = substr_replace($subject, '', 0, 7); 
      $subject = str_replace("\r\n", '&', $subject); 
      parse_str($subject, $result); 

      return array(count($result), array_shift($result), array_shift($result)); 
     } 
     return FALSE; 
    } 

    // http://stackoverflow.com/questions/3964219/3964520#3964520 
    public function bench_mellowsoon($subject) 
    { 
     $subject = urldecode($subject); 

     $lines = explode("\r\n", $subject); 
     $lines = array_map('trim', $lines); 
     $status = array_shift($lines); 
     if($status == 'SUCCESS') 
     { 
      $result = array(); 
      foreach($lines as $line) 
      { 
       list($key, $value) = explode('=', $line, 2); 
       $result[$key] = $value; 
      } 
      return array(count($result), array_shift($result), array_shift($result)); 
     } 

     return FALSE; 
    } 

    // http://stackoverflow.com/questions/3964219/3964265#3964265 
    public function bench_amber($subject) 
    { 
     if(strpos($subject, 'SUCCESS') === 0) 
     { 
      $subject = explode("\r\n", urldecode($subject)); 
      array_shift($subject); // Remove is empty 

      $result = array(); 
      foreach($subject as $line) 
      { 
       $bits = explode('=', $line); 
       $field_name = array_shift($bits); 
       $field_contents = implode('=', $bits); 
       $result[$field_name] = $field_contents; 
      } 
      return array(count($result), array_shift($result), array_shift($result)); 
     } 
     return FALSE; 
    } 

    // http://stackoverflow.com/questions/3964219/3964366#3964366 
    public function bench_GigaWatt($subject) 
    { 
     if(strpos($subject, 'SUCCESS') === 0) 
     { 
      $subject = explode("\r\n", urldecode($subject)); 

      $result = array(); 
      foreach($subject as $line) 
      { 
       if (strpos($line, "=") === FALSE) 
        continue; 

       list($var, $value) = explode("=", trim($line)); 
       $result[$var] = empty($value) ? NULL : $value; 
      } 
      return array(count($result), array_shift($result), array_shift($result)); 
     } 
     return FALSE; 
    } 

    // http://stackoverflow.com/questions/3964219/3964366#3964366 
    public function bench_GigaWatt2($subject) 
    { 
     if(strpos($subject, 'SUCCESS') === 0) 
     { 
      $subject = explode("\r\n", urldecode($subject)); 

      $result = array(); 
      foreach($subject as $line) 
      { 
       if (strpos($line, "=") === FALSE) 
        continue; 

       list($var, $value) = explode("=", trim($line)); 
       $result[$var] = $value; 
      } 
      return array(count($result), array_shift($result), array_shift($result)); 
     } 
     return FALSE; 
    } 

    // http://stackoverflow.com/questions/3964219/3964323#3964323 
    public function bench_dvhh($subject) 
    { 
     if(strpos($subject, 'SUCCESS') === 0) 
     { 
      $subject = explode("\r\n", urldecode($subject)); 

      $result = array(); 
      foreach($subject as $line) 
      { 
       $lineData = preg_split("/\s*=\s*/", $line); 
       if(count($lineData) == 2) 
       { 
        $result[$lineData[0]] = $lineData[1]; 
       } 
      } 
      return array(count($result), array_shift($result), array_shift($result)); 
     } 
     return FALSE; 
    } 


    public $subjects = array 
    (
     "SUCCESS\r\[email protected]\r\ncharset=windows-1252\r\ncustom=\r\nfirst_name=Alice\r\nhandling_amount=0.00\r\ninvoice=AF000001\r\nitem_name=Stuffed bear\r\nitem_number=BEAR05\r\nlast_name=Foobar\r\nmc_currency=USD\r\nmc_fee=2.00\r\nmc_gross=20.00\r\[email protected]\r\npayer_id=UC9DXVX7GRSTN\r\npayer_status=unverified\r\npayment_date=09:08:06 Oct 18, 2010 PDT\r\npayment_fee=\r\npayment_gross=\r\npayment_status=Completed\r\npayment_type=instant\r\nprotection_eligibility=Ineligible\r\nquantity=1\r\nreceipt_id=2479-2605-1192-2880\r\[email protected]\r\nreceiver_id=8Y670ENTB8BY6\r\nresidence_country=USD\r\nshipping=0.00\r\ntax=0.00\r\ntransaction_subject=Bear\r\ntxn_id=1PH815997L239283J\r\ntxn_type=web_accept", 

     "FAIL\r\nError: 4003", 

     "INVALID", 
    ); 
} 

如果任何人有任何改进的进一步的建议,请让我知道分开:)

+1

PHP将把“”和NULL作为大多数操作是相同的,所以这不是什么可担心的。 – mellowsoon 2010-10-19 00:26:05

+0

是的,只是不要使用完全匹配('==='),它应该是好的。 – tonyhb 2010-10-19 00:30:07

回答

0

这是我怎么会做它在5行:

 
// Is this a successful post? 
if(substr($paypal, 0, 7) == 'SUCCESS') 
{ 
    $paypal = substr_replace($paypal, '', 0, 7); 
    $paypal = str_replace(array("\n", "\r", "\r\n"), '&', $paypal); 
    parse_str($paypal, $response_array); 
} 

检查,看是否回发$paypal是成功的,如果它是&除去第一线,替换换行符然后运行它通过parse_str,排序。输出在$response_array准备摇摆。

与琥珀相同的问题,但是,其中NULL显示为''

编辑:另外,一个警告:如果数组键有任何特殊字符(由于某种奇怪的原因,可能是.)它会转换为_

+0

现在* *很有趣......在一百万年内不会有这样的东西:p – Svish 2010-10-19 01:17:36

+0

哦,这也照顾了urldecoding。已经忘记了这一点。好吧:) – Svish 2010-10-19 01:45:13

+1

'strpos($ subject,'SUCCESS')=== 0'比substr($ paypal,0,7)更快=='SUCCESS'' – Svish 2010-10-19 01:51:46

2

分裂出去的第一线,检查它,然后用它来抓取休息:

foreach($response_lines as $line) { 
    $bits = explode('=', $line); 
    $field_name = array_shift($bits); 
    $field_contents = implode('=', $bits); 
    $fields[$field_name] = $field_contents; 
} 

之后$fields将是您寻求的数组。 (一个注意:响应中没有值的项目将具有''而不是NULL。)

+1

通过使用2作为explode()的第三个参数,即爆炸('=',$ line,2),你可以截取几行代码。这可以防止字符串被分成两个以上的部分。 – mellowsoon 2010-10-19 00:24:59

0

使用http://www.php.net/manual/en/function.preg-split.php

foreach($lines as $line) { 
    $lineData = preg-split("\s*=\s*",$line); 
    if(count($lineData)==2) { 
     $result[$lineData[0]] = $lineData[1]; 
    } 
} 
+0

从php.net - >如果你不需要正则表达式的力量,你可以选择像explode()或str_split()那样更快(尽管更简单)的选择。 – mellowsoon 2010-10-19 00:23:00

+0

@mellowsoon:有时正则表达式可能会更快,但很有可能不会在这种情况下,不会... – Svish 2010-10-19 01:29:41

0

下面的工作:

foreach($response as $line) { 
    if (strpos($line, "=") === FALSE) { continue; } // Skip the line if there's no assignment action going on. 
    list($var, $value) = explode("=", trim($line)); // Get the parts on either side of the "=". 
    $result[$var] = (empty($value) ? NULL : $value); // Assign the value to the result array, making the value NULL if it's empty. 
} 
+0

您是第一个将空值设置为NULL的好主意:)如果线条具有空值,则不应跳过线条。另外,你应该为爆炸极限加2。 – Svish 2010-10-19 01:55:27

0

添加我的2美分,因为一些至今发布的解决方案都过于聪明的,或不是100%正确。

$lines = explode("\n", $paypal_response); 
$lines = array_map('trim', $lines); 
$status = array_shift($lines); 
if ($status != 'SUCCESS') { 
    // Transaction was not successful 
} 
$values = array(); 
foreach($lines as $line) { 
    list($key, $value) = explode('=', $line, 2); 
    $values[$key] = $value; 
} 
0

这里是一个更复杂的解决方案:

//$result=the result from paypal 
parse_str(str_replace(PHP_EOL,'&',$result),$result); 
var_dump($result); 
相关问题