使用PHP将String对象转换为数组

时间:2012-02-05 08:35:35

标签: php arrays object

很奇怪,我从某些API获得以下字符串:

parseresponse({"eurusd":{ "id": "eurusd", "category": "Forex", "price": 1.3161, "name": "EUR/USD", "buy": 1.3162, "sell": 1.3159, "change": 0.00, "date":1328288216000}});

出于某种原因,我在使用时无法将其替换为Array:

var_dump(json_decode($content));

我也尝试使用php函数:

function object2array($object) {
if (is_object($object)) foreach ($object as $key => $value) $array[$key] = $value;
    else $array = $object;
return $array;
}

任何想法?..

2 个答案:

答案 0 :(得分:2)

您尝试将JSONP响应解析为JSON,您应首先删除包装功能。

$response = 'parseresponse({"eurusd":{ "id": "eurusd", "category": "Forex", "price": 1.3161, "name": "EUR/USD", "buy": 1.3162, "sell": 1.3159, "change": 0.00, "date":1328288216000}});';
$json = preg_replace('/^parseresponse\((.*)\);/', '$1', $response);
$data = json_decode($json, true);
print_r($data);

答案 1 :(得分:0)

您可以尝试这样的事情:

$content = '{"eurusd":{ "id": "eurusd", "category": "Forex", "price": 1.3161, "name": "EUR/USD", "buy": 1.3162, "sell": 1.3159, "change": 0.00, "date":1328288216000}}';

function toArray($data) {
    if (is_object($data)) $data = get_object_vars($data);
    return is_array($data) ? array_map(__FUNCTION__, $data) : $data;
    }

$newData = toArray (json_decode($content));

print_r($newData);

输出将是:

阵 (     [eurusd] =>排列         (             [id] =>欧元兑美元             [category] ​​=>外汇             [price] => 1.3161             [name] =>欧元/美元             [buy] => 1.3162             [sell] => 1.3159             [更改] => 0             [date] => 1328288216000         )