如何将这些值转换为数组或对象

时间:2011-11-17 10:41:01

标签: php

我有一些数据,我使用base64_decode解码。解码后,我得到了这样的值:

{ 
    "quantity" = "1"; 
    "product-id" = "gigaplex.subscription.monthly"; 
    "item-id" = "421702921"; 
    "version-external-identifier" = "4000187"; 
    "purchase-date" = "2011-08-09 18:38:52 Etc/GMT"; 
    "app-item-id" = "421702836"; 
    "transaction-id" = "30000011473303"; 
    "original-purchase-date" = "2011-08-09 18:38:52 Etc/GMT"; 
    "original-transaction-id" = "30000011473303"; 
    "bid" = "com.gigaplex.gigaplexHD"; 
    "bvrs" = "1.4"; 
}

但我的问题是我无法从此字符串中提取指定的值。请提出一些建议来提取这个...

3 个答案:

答案 0 :(得分:1)

使用几个str_replace函数将其转换为json,然后对其进行解码:

<?php

$testval = '{ 
   "quantity" = "1"; 
   "product-id" = "gigaplex.subscription.monthly"; 
   "item-id" = "421702921"; 
   "version-external-identifier" = "4000187"; 
   "purchase-date" = "2011-08-09 18:38:52 Etc/GMT"; 
   "app-item-id" = "421702836"; 
   "transaction-id" = "30000011473303"; 
   "original-purchase-date" = "2011-08-09 18:38:52 Etc/GMT"; 
   "original-transaction-id" = "30000011473303"; 
   "bid" = "com.gigaplex.gigaplexHD"; 
   "bvrs" = "1.4";}';

$testval = str_replace('";','",',$testval); // replace the colons
$testval = str_replace(' = ',' : ',$testval);  // replace the equals
$testval = substr($testval,0,-2) . '}';  // remove the final comma

var_dump(json_decode($testval));

http://codepad.org/kOc862aD

**有效,但我确信可以改进

答案 1 :(得分:1)

使用正则表达式的另一种解决方案

$data = '{ 
   "quantity" = "1"; 
   "product-id" = "gigaplex.subscription.monthly"; 
   "item-id" = "421702921"; 
   "version-external-identifier" = "4000187"; 
   "purchase-date" = "2011-08-09 18:38:52 Etc/GMT"; 
   "app-item-id" = "421702836"; 
   "transaction-id" = "30000011473303"; 
   "original-purchase-date" = "2011-08-09 18:38:52 Etc/GMT"; 
   "original-transaction-id" = "30000011473303"; 
   "bid" = "com.gigaplex.gigaplexHD"; 
   "bvrs" = "1.4"; 
}';

preg_match_all('/"([^"]*)"\s*=\s*"([^"]*)"/', $data, $matches );

$data = array_combine( $matches[1], $matches[2] );
print_r( $data );

/*
Array
(
    [quantity] => 1
    [product-id] => gigaplex.subscription.monthly
    [item-id] => 421702921
    [version-external-identifier] => 4000187
    [purchase-date] => 2011-08-09 18:38:52 Etc/GMT
    [app-item-id] => 421702836
    [transaction-id] => 30000011473303
    [original-purchase-date] => 2011-08-09 18:38:52 Etc/GMT
    [original-transaction-id] => 30000011473303
    [bid] => com.gigaplex.gigaplexHD
    [bvrs] => 1.4
)
*/

答案 2 :(得分:0)

将字符串分解为/ r / n字符上的数组。然后在“=”标记上拆分字符串,最后修剪空格和“字符”上的结果字符串对,只留下一组很好的键和值对!

$lines = explode('/r/n', $string);
$results = Array();
foreach($lines as $line) {
    list($key, $value) = preg_split('@" = "@', $line);
    $key = trim($key, ' "');
    $value = trim($value, ' "');
    $results[$key] = $value;
}

(未经测试;))