如何将JSON响应转换为PHP数组

时间:2014-04-13 04:41:30

标签: php

我试图将此响应转换为PHP数组:

string(734) " {"definitions":[{"text":"Informal One who is proficient at using or programming a computer; a computer buff.","attribution":"from The American Heritage\u00ae Dictionary of the English Language, 4th Edition"},{"text":"Informal One who uses programming skills to gain illegal access to a computer network or file.","attribution":"from The American Heritage\u00ae Dictionary of the English Language, 4th Edition"},{"text":"Informal One who enthusiastically pursues a game or sport: a weekend tennis hacker. ","attribution":"from The American Heritage\u00ae Dictionary of the English Language, 4th Edition"},{"text":"See hackie.","attribution":"from The American Heritage\u00ae Dictionary of the English Language, 4th Edition"}]}"

我已尝试过

的所有内容

$string = $result; $pattern = '\w*\(\d+\)\s'; $replacement = ''; preg_replace($pattern,$replacement,$string)

$string = $result; $pattern = '\w*\(\d+\)\s'; $replacement = ''; $def_array = str_replace($pattern,$replacement,$string);

但是当我这样做时,他们甚至不会改变原来的结果。

我希望实现这样的目标: $def_array = {"definitions":[{"text":"Informal One who is proficient at using or programming a computer; a computer buff.","attribution":"from The American Heritage\u00ae Dictionary of the English Language, 4th Edition"},{"text":"Informal One who uses programming skills to gain illegal access to a computer network or file.","attribution":"from The American Heritage\u00ae Dictionary of the English Language, 4th Edition"},{"text":"Informal One who enthusiastically pursues a game or sport: a weekend tennis hacker. ","attribution":"from The American Heritage\u00ae Dictionary of the English Language, 4th Edition"},{"text":"See hackie.","attribution":"from The American Heritage\u00ae Dictionary of the English Language, 4th Edition"}]}

我想通过这样的定义:

for($i = 0; $i < sizeof($def_array[0]["definitions"]); $i++) { echo $def_array[0]["definitions"][$i]["text"]; echo "\n"; }

我没有使用json_decode,因为当我这样做时,我得到错误Fatal error: Cannot use object of type stdClass as array on the line($ i = 0; $ i&lt; sizeof($ def_array [0] [&#34;定义&#34} ;]); $ i ++)`。

2 个答案:

答案 0 :(得分:4)

为什么不只是json_decode()函数。

$array = json_decode($input);

在此处查找更多信息:http://www.php.net/manual/en/function.json-decode.php

答案 1 :(得分:0)

Parse error on line 1:
"{    "definitions"
^
Expecting '{', '['

格式无效,必须以{或[

开头