您好我想在从api发布的表中插入值 json数据是
{"questions":{"34":"Yes", "46":"good", "48":"NA", "29":"Yes", "45":"ravi", "49":"Negative", "43":"1 BHK", "35":"Neighbour", "38":"14", "39":"9", "27":"1",
"41":"Married", "52":"vijay@123.com", "47":"good", "31":"Bunglow", "33":"Middle Class", "37":"Owned By Parents", "30":"good", "50":"easy",
"51":"comments", "32":"No", "44":"[MusicSystem,PC,Refrigerator,Airconditioner]"}}
当我转换成数组时,它是
Array
(
[questions] => Array
(
[34] => Yes
[46] => good
[48] => NA
[29] => Yes
[45] => ravi
[49] => Negative
[43] => 1 BHK
[35] => Neighbour
[38] => 14
[39] => 9
[27] => 1
[41] => Married
[52] => ravi@gmail.com
[47] => good
[31] => Bunglow
[33] => Middle Class
[37] => Owned By Parents
[30] => good
[50] => easy
[51] => comments
[32] => No
[44] => [MusicSystem,PC,Refrigerator,Airconditioner]
)
)
如何获得像
这样的值使用foreach $问题= 34; $ answer = yes;
答案 0 :(得分:2)
尝试这样。使用json_decode()
将json转换为数组。然后使用键和值创建一个新数组。然后只打印第一个键和值。
<?php
$json = '{"questions":{"34":"Yes", "46":"good", "48":"NA", "29":"Yes", "45":"ravi", "49":"Negative", "43":"1 BHK", "35":"Neighbour", "38":"14", "39":"9", "27":"1",
"41":"Married", "52":"vijay@123.com", "47":"good", "31":"Bunglow", "33":"Middle Class", "37":"Owned By Parents", "30":"good", "50":"easy",
"51":"comments", "32":"No", "44":"[MusicSystem,PC,Refrigerator,Airconditioner]"}}
';
$array = json_decode($json,TRUE);
//print_r($array);
foreach($array['questions'] as $key=>$value)
{
$arr[] = array('key'=>$key,'value'=>$value);
}
//print_r($arr);
echo "Question:".$arr[0]['key'].PHP_EOL;
echo "Answer:".$arr[0]['value'];
输出:
Question:34
Answer:Yes
答案 1 :(得分:0)
要在拥有密钥时访问单个值,您可以$array["questions"][34]
获得答案yes
。
如果你想循环遍历所有这些循环:
foreach($array["questions"] as $no => $ans){
echo "Question: $no";
echo "Answer: $ans";
}