访问$ x-> output-> 0->操作的问题为 - > 0->不起作用

时间:2014-11-27 23:11:44

标签: php json

请问我如何解析这个json回复:

{ "info": { "apiVersion": "1.1", "clientFeatures": ["all"], "clientTime": "2014-11-27T23:04:27.542Z", "emotions": [], "input": "who+created+you", "isNewUser": true, "locale": "en", "location": "53.0%2C9.0", "login": "mashape", "responseTime": 948 }, "output": [{ "actions": { "custom": {}, "say": {"text": "I was created by the cool guys from Pannous."} }, "entities": { "dialoguesInfo": { "dialog": "Sandbox", "dialog_id": "63", "forced": false, "initiative": false, "match_id": "205233", "matchscore": "3.77", "response_id": "205224" }, "input": "who+created+you", "locale": "en" }, "responseTime": 673, "results": {} }] }

我想得到结果:output-> actions-> say。

我已经尝试过:$req = $response -> raw_body; foreach($req as $ob->$val){} 但没有工作。

我也试过json_decode但是没有工作。

1 个答案:

答案 0 :(得分:1)

正如Tomasz Kowalczyk已经建议的那样,json_decode是一个伟大的本土功能。

有时,当代码无法按照您的预期运行时会感到沮丧,但人们确实在努力提供帮助。当某些内容无法按照您希望的方式运行时,请确保包含它对您不起作用的方式

$x = '{ "info": { "apiVersion": "1.1", "clientFeatures": ["all"], "clientTime": "2014-11-27T23:04:27.542Z", "emotions": [], "input": "who+created+you", "isNewUser": true, "locale": "en", "location": "53.0%2C9.0", "login": "mashape", "responseTime": 948 }, "output": [{ "actions": { "custom": {}, "say": {"text": "I was created by the cool guys from Pannous."} }, "entities": { "dialoguesInfo": { "dialog": "Sandbox", "dialog_id": "63", "forced": false, "initiative": false, "match_id": "205233", "matchscore": "3.77", "response_id": "205224" }, "input": "who+created+you", "locale": "en" }, "responseTime": 673, "results": {} }] }';

json_decodevar_dump看到输出。

var_dump(json_decode($x));

结果:

class stdClass#1 (2) { public $info => class stdClass#2 (10) { public $apiVersion => string(3) "1.1" public $clientFeatures => array(1) { [0] => string(3) "all" } public $clientTime => string(24) "2014-11-27T23:04:27.542Z" public $emotions => array(0) { } public $input => string(15) "who+created+you" public $isNewUser => bool(true) public $locale => string(2) "en" public $location => string(10) "53.0%2C9.0" public $login => string(7) "mashape" public $responseTime => int(948) } public $output => array(1) { [0] => class stdClass#3 (4) { public $actions => class stdClass#4 (2) { ... } public $entities => class stdClass#7 (3) { ... } public $responseTime => int(673) public $results => class stdClass#9 (0) { ... } } } }

如您所见,json_decode工作正常。要完整地汇总数据,而不是var_dump,请执行上述操作,但请使用print_r

请记住,如果您希望将解码数据作为数组,请使用json_decode($yourData, true)

从这里开始,现在应该非常清楚,如何访问您想要的数据。如果不是,不用担心,解决方案已经接近,只需写下关于哪些部分让您感到困惑的评论。

SPOILER

我在这里为你添加了一小段代码https://eval.in/227351 基本上,0偏移是给你带来困难的......

$foo = json_decode($x, TRUE); var_dump($foo['output'][0]['actions']);