从 PHP 中的 JSON 数组获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17995877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get value from JSON array in PHP
提问by Kim
I'm trying to get the value from this following JSON array in a PHP variable.
我正在尝试从 PHP 变量中的以下 JSON 数组中获取值。
This is a var_dump of the array:
这是数组的 var_dump:
array(3) {
["id"]=>
string(2) "14"
["css"]=>
string(400) ""
["json"]=>
string(4086) "
{
"Canvas": [
{
"MainObjects": {
"After Participation": {
"afterParticipationHeader": "Thank you!"
},
"Invite Friends": {
"InviteHeadline": "",
"InviteMsg": "",
"InviteImg": ""
}
},
"QuizModule": {
"Questions": [],
"Submit_Fields": [
{
"label": "Name",
"name": "txtName",
"value": true
}
]
}
}
]
}"
}
I am able to get the values for ["json"] in PHP like:
我能够在 PHP 中获取 ["json"] 的值,例如:
$json = $data[0]['json'];
But how do I get the value from from the array inside "json", like "AfterParticipationHeader". And "Submit_Fields" ?
但是如何从“json”中的数组中获取值,例如“AfterParticipationHeader”。和“Submit_Fields”?
回答by som
First you have to decode your json data
首先你必须解码你的json数据
$json = json_decode($data[0]['json']);
Then you can access your AfterParticipationHeader
然后你可以访问你的 AfterParticipationHeader
$json->Canvas[0]->MainObjects->{"After Participation"}->afterParticipationHeader
回答by NDM
you can convert a valid JSON string to a PHP variable with json_decode(). Note the second parameter to get an assoc array
instead of the less usefull stdClass
.
您可以使用json_decode()将有效的 JSON 字符串转换为 PHP 变量。请注意获取 assocarray
而不是不太有用的第二个参数stdClass
。
$jsonData = json_decode($data[0]['json'], true);
$header = $jsonData['Canvas']['MainObjects']['After Participation']['afterParticipationHeader'];
回答by Maxime Lorant
You can decode the JSON via the json_decodefunction:
您可以通过json_decode函数解码 JSON :
$json = json_decode($data[0]['json']);
Then, you'll have arrays (in the same structure) with your data.
然后,您将拥有包含数据的数组(在相同的结构中)。
回答by dan
It looks like you need to decode it. Try using: $json = json_decode($data[0]['json']);
看来您需要对其进行解码。尝试使用:$json = json_decode($data[0]['json']);
Let me know if this helps.
如果这有帮助,请告诉我。