使用PHP解析来自JSON回调的数据

时间:2018-01-05 08:03:46

标签: php json

我从付款网站收到回调数据,并尝试将一些值保存到txt文件

获取数组:

$json = file_get_contents('php://input');

$obj = json_decode($json,true);

将所有数据保存到txt:

file_put_contents('robot.php', var_export($obj, true) . "\r\n\r\n", FILE_APPEND | LOCK_EX);

来自txt的结果:

array (
  'rrn' => '',
  'masked_card' => '444455XXXXXX1111',
  'sender_cell_phone' => '',
  'response_status' => 'success',
  'sender_account' => '',
  'fee' => '',
  'rectoken_lifetime' => '',
  'reversal_amount' => '0',
  'settlement_amount' => '0',
  'actual_amount' => '370000',
  'order_status' => 'approved',
  'response_description' => '',
  'verification_status' => '',
  'order_time' => '04.01.2018 21:53:47',
  'actual_currency' => 'JPY',
  'order_id' => 1515095627',
  'parent_order_id' => '',
  'merchant_data' => '[{"name":"custom-field-0","label":"fist_name","value":"john_doe"},{"name":"custom-field-2","label":"phone","value":"07777777777"}]',
  'tran_type' => 'purchase',
  'eci' => '5',
  'settlement_date' => '',
  'payment_system' => 'card',
  'rectoken' => '',
  'approval_code' => '56783909',
  'merchant_id' => 14066776208,
  'settlement_currency' => '',
  'payment_id' => 7487818gg3,
  'product_id' => '',
  'amount' => '370000',
  'sender_email' => 'admin@none.in.ua',
)

如何从嵌套数组'merchant_data'中保存txt单独的值 - 名字和电话?

1 个答案:

答案 0 :(得分:2)

您可以创建新数组并将其保存到文件:

$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$save = [];
foreach ($obj['merchant_data'] as $data){
    $save[] = [
        'name' => $data['first_name'],
        'phone' => $data['phone'],
    ];
}
file_put_contents('robot.php', var_export($save, true) . "\r\n\r\n", FILE_APPEND | LOCK_EX);