{“signature”=“Alof / CEJ8a ==”; “purchase-info”=“ewoJIml0”; “环境”=“测试”; “pod”=“100”; “签名状态”=“0”; }
PHP将这个iPhone应用内购买交易帖子解析为数组的最佳方法是什么?感谢。
答案 0 :(得分:2)
不确定这是“最佳”方式,但这是一种方式。由于数据字符串由公共字符(由;
设置的每个键/值,然后是键/值之间的=
)分隔,因此大部分解析可以使用{{3}完成}。您可以使用explode()
- 使用自定义字符列表 - 删除整个字符串周围的额外字符以及键/值。
请注意,这会使密钥永远不会有=
(尽管值可能是):
$data = '{ "signature" = "Alof/CEJ8a=="; "purchase-info" = "ewoJIml0"; "environment" = "Test"; "pod" = "100"; "signing-status" = "0"; }';
//remove the braces, spaces, and trailing semicolon
$data = trim($data, '{}; ');
$array = array();
//split on ';'
foreach(explode(';', $data) as $set){
//parse key/value
list($key, $value) = explode('=', $set, 2);
$array[trim($key, '"\' ')] = trim($value, '"\' ');
}
print_r($array);
输出:
Array
(
[signature] => Alof/CEJ8a==
[purchase-info] => ewoJIml0
[environment] => Test
[pod] => 100
[signing-status] => 0
)
答案 1 :(得分:1)
您可以将:'s替换为:'s和; s替换为's,然后使用json_decode()。
像这样:
$data = '{ "signature" = "Alof/CEJ8a=="; "purchase-info" = "ewoJIml0"; "environment" = "Test"; "pod" = "100"; "signing-status" = "0"; }';
$data = explode('" =',$data);
$data = implode('" :',$data);
$data = explode(';',$data);
array_pop($data);
$data = implode(',',$data);
$data = explode(' ',$data);
$data = implode('',$data);
$data .= "}";
$data = json_decode($data, true);
查看here。
答案 2 :(得分:1)
$data = '{ "signature" = "Alof/CEJ8a=="; "purchase-info" = "ewoJIml0"; "environment" = "Test"; "pod" = "100"; "signing-status" = "0"; }';
$search = array('/\s\=\s/', '/;\s\}$/', '/;/');
$replace = array(':', '}', ',');
$json = preg_replace($search, $replace, $data);
print_r(json_decode($json));
输出:
Array
(
[signature] => Alof/CEJ8a==
[purchase-info] => ewoJIml0
[environment] => Test
[pod] => 100
[signing-status] => 0
)