我正在尝试将json字符串输入为: http://prntscr.com/kt8i8a
{"0":168,"1":168}
{"168":1,"168":2}
{"168":70000,"168":80000}
我的目的是获取id = 168的2个值保存在数据库中
当我使用json_decode('{"168":1,"168":2}',true)
时
我得到的结果只有值:
array:1 [
168 => 2
]
解析完整值的方法有哪些?谢谢
答案 0 :(得分:4)
对象/词典中的键是唯一的,因此最后一个键的值将是最终值,并替换之前的所有其他值。
两种解决方案,要么将2个对象放入一个数组中:
[
{
"168": "1"
},
{
"168": "2"
}
]
或具有键为168
且具有2个值的对象:
{
"168": [
"1",
"2"
]
}
答案 1 :(得分:1)
在您的情况下,我希望您可以修改编码的json的格式,并添加一些额外的信息以使其成为多维数组。具有相同值的键索引有不同的方法,一种可能是这样的:
{"data":
[
{"168":"1"},{"168":"2"}
]
}
在这种情况下,您可以获得所需的结果并访问值,否则就不可能像代码中那样,因为您有重复的唯一键索引。 希望是明确的,对您有帮助。
答案 2 :(得分:-2)
这不是有效的json语法,请尝试对其进行修复。
如果您因为未开发而无法影响api而不能这样做,则可以通过regex解析进行尝试,如下所示:
<?php
//print out the result
var_dump(getInvalidCustomJson('{"0":168,"1":168}'));
function getInvalidCustomJson($json){
$res = array(); // result array which get returned
preg_match_all('/"([0-9]+)".([0-9]+)/m',$json, $result, PREG_PATTERN_ORDER); // matching a key between "..." and a value which get send afterwards
for($i = 0; $i < count($result[0]); $i++){ // go through all results
$std = array();
$std[$result[1][$i]] = $result[2][$i]; // insert key and value from the groups into the array
$res[] = $std; // add the array to the result array
// $res[$result[1][$i]] = $result[2][$i]; wont work because it will
// overwrite the key like json decoder does
}
return $res; // return array
}
?>