我正在尝试使用PHP和Paypal的NVP TransactionSearch
方法显示一系列交易。
我成功地显示了交易,但我无法整理响应并仅显示我之后的特定值 - 在这种情况下,每个事务只有以下4个值:
L_TIMESTAMP,
L_TYPE,
L_TRANSACTIONID
我目前的代码是:
$request = http_build_query(array(
"METHOD" => $action,
"VERSION" => $config['version'],
"USER" => $config['username'],
"PWD" => $config['password'],
"SIGNATURE" => $config['signature'],
"STARTDATE" => $start,
"EMAIL" => $email,
));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$result = curl_exec($ch);
if (!$result) {
echo 'no results';
}
parse_str($result, $result);
foreach($result as $key => $value){
echo $key.' => '.$value."<br />";
}
将一切输出如下:
L_TIMESTAMP0 => 2014-01-15T11:29:21Z
L_TIMESTAMP1 => 2014-01-15T11:09:05Z
L_TIMEZONE0 => GMT
L_TIMEZONE1 => GMT
L_TYPE0 => Refund
L_TYPE1 => Payment
L_TRANSACTIONID0 => 7MY22222222222914
L_TRANSACTIONID1 => 2045555555555594D
and so on...
我怎么能这样输出呢:(所以它经历了每个事务然后是下一个而不是每个'值'到下一个,再加上不显示TIMEZONE键)
L_TIMESTAMP0 => 2014-01-15T11:29:21Z
L_TYPE0 => Refund
L_TRANSACTIONID0 => 7MY22222222222914
L_TIMESTAMP1 => 2014-01-15T11:09:05Z
L_TYPE1 => Payment
L_TRANSACTIONID1 => 2045555555555594D
答案 0 :(得分:3)
我认为数组数组将是更好的选择:
foreach($result as $k => $v) {
preg_match('~([A-Z_]+)(\d+)$~', $k, $m);
$nested[$m[2]][$m[1]] = $v;
}
创建一个这样的嵌套数组:
Array
(
[0] => Array
(
[L_TIMESTAMP] => 2014-01-15T11:29:21Z
[L_TIMEZONE] => GMT
[L_TYPE] => Refund
[L_TRANSACTIONID] => 7MY22222222222914
)
[1] => Array
(
[L_TIMESTAMP] => 2014-01-15T11:09:05Z
[L_TIMEZONE] => GMT
[L_TYPE] => Payment
[L_TRANSACTIONID] => 2045555555555594D
)
)
从中生成所需的输出应该很容易。
答案 1 :(得分:0)
您可以在包装循环中使用array_filter
。像这样:
for ($i = 0; ; $i++) {
$arr = array_filter($result, function ($v) use ($i) {
return substr($v, -1) == $i;
});
if (!$arr) break;
foreach($arr as $key => $value){
echo $key.' => '.$value."<br />";
}
}