试图从PHP中的数组中获取值时完全陷入困境
我一直试图弄清楚如何使用 PHP 在这个数组中获取 'text' 的值,经过多次尝试,我还没有到放弃的阶段。
有人能告诉我如何从这个数组中获取 'text' 中的翻译文本吗?它是在 Microsoft Azure 翻译服务上使用 REST API 返回的,并且根据文档是一个 JSON 对象,但无论我尝试什么,我都无法使用代码从数组的任何部分获取任何文本。在我失去剩下的头发之前,将非常感谢指针!
Array
(
[0] => stdClass Object
(
[detectedLanguage] => stdClass Object
(
[language] => en
[score] => 1
)
[translations] => Array
(
[0] => stdClass Object
(
[text] => Entrez votre texte ici
[to] => fr
)
)
)
)
回答
在 PHP 中,对象通过箭头访问->,数组通过方括号访问[]。
您可以看到每个都标记为stdClass Object或Array。因此,请按如下方式处理响应:
$response[0]->translations[0]->text
为了打破它...
$response[0]
stdClass Object
(
[detectedLanguage] => stdClass Object
(
[language] => en
[score] => 1
)
[translations] => Array
(
[0] => stdClass Object
(
[text] => Entrez votre texte ici
[to] => fr
)
)
)
$response[0]->translations
Array
(
[0] => stdClass Object
(
[text] => Entrez votre texte ici
[to] => fr
)
)
$response[0]->translations[0]
stdClass Object
(
[text] => Entrez votre texte ici
[to] => fr
)
$response[0]->translations[0]->text
Entrez votre texte ici
我希望这个奇怪的例子有帮助!