我有一个json字符串i,它在一个对象中有一个json数组和另一个对象,我想先将json数组转换为php数组,然后再将另一个json对象转换为php变量。请告诉我该怎么做。我有stdclass,但是我无法获得准确的数据。
杰森·斯特林
{
"data": [
{
"ques_name": "no",
"ques_id": "1"
}, {
"ques_name": "yes",
"ques_id": "2"
}, {
"ques_name": "no",
"ques_id": "3"
}, {
"ques_name": "yes",
"ques_id": "4"
}, {
"ques_name": "no",
"ques_id": "5"
}, {
"ques_name": "yes",
"ques_id": "6"
}, {
"ques_name": "no",
"ques_id": "7"
}
],
"UserId": 163
}
我使用以下代码来获取数组,但它给了我大小为14的数组,其中大小应为7
$params=$_GET['params'];
$arr=array();
$decode=json_decode($params);
$arr=$decode->data;
print_r($arr);
参考方案
json_decode($array)
将您的json对象转换为数组。
编辑:
您可以尝试json_decode($array, true);
。这样,返回的对象将被转换为关联数组。
Edit2:使用我在编辑部分(json_decode($array, true);
)中的代码,我得到以下数组(对我来说似乎不错):
Array
(
[data] => Array
(
[0] => Array
(
[ques_name] => no
[ques_id] => 1
)
[1] => Array
(
[ques_name] => yes
[ques_id] => 2
)
[2] => Array
(
[ques_name] => no
[ques_id] => 3
)
[3] => Array
(
[ques_name] => yes
[ques_id] => 4
)
[4] => Array
(
[ques_name] => no
[ques_id] => 5
)
[5] => Array
(
[ques_name] => yes
[ques_id] => 6
)
[6] => Array
(
[ques_name] => no
[ques_id] => 7
)
)
[UserId] => 163
)
Edit3:关于如何获取数组的id / name部分的问题,下面是一个小示例代码:
$jsonData= ''; // put here your json object
$arrayData = json_decode($jsonData, true);
if (isset($arrayData['data']))
{
foreach ($arrayData['data'] as $data)
{
echo 'id='.$data['ques_id'].', name='.$data['ques_name'].'<br>'
}
}
PHP-复选框组 - php我有一个需要发布的表单复选框组。<input type="checkbox" value="true" checked name="chk0[]"> <input type="checkbox" value="false" name=…
PHP Count数组元素 - php嗨,有人可以解释为什么这会返回“数组由0个元素组成”。 :$arr = array(1,3,5); $count = count($arr); if ($count = 0) { echo "An array is empty."; } else { echo "An array has $count elements.…
PHP:从函数返回值并直接回显它? - php这可能是一个愚蠢的问题,但是……的PHPfunction get_info() { $something = "test"; return $something; } html<div class="test"><?php echo get_info(); ?></div> 有没有办…
PHP:将数据从二维数组复制到一维数组的最快方法 - php我有一个巨大的二维PHP数组,带有500万行。$t = [ [ "id" => 1, "name" => "foo" ], [ "id" => 2, "name" => "bar" ] ]; 现在,我必须将此数组的I…
php-printf和sprintf具有不同的输出 - php我编写了以下微型php程序来测试printf和sprintf:<?php $str_1 = printf("%x%x%x", 65, 127, 245); $str_2 = sprintf("%x%x%x", 65, 127, 245); echo $str_1 . "\n"; echo $s…