PHP: Extract value from JSON array

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

I have an API that takes parameters from a post through JSON and I want to extract one of the values in an array for a key value pair. However, despite many attempts, I can't get it to work.

Here is my code:

$json = file_get_contents('php://input');  $request = json_decode($json, true); $parameters = $request["result"]["parameters"]; 

When I log $parameters to a text file, it log as

 {"numberofhits":"5"} 

However, my efforts to capture the value 5 are not working:

$numhits = $json['numberofhits']; logs as empty. 

So does:

$numhits = $parameters->numberofhits; 

How can I capture the value 5 in a variable?

回答1:

From your code above $json is a string and not a json object, your should use $request to access numberofhits

$request['numberofhits'] 


回答2:

If your $parameters just shows {"numberofhits":"5"}, this means your post request just returned a json of a json. Try json decoding $parameters again like json_decode($parameters, true); and log that result. It should log the desired array.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!