JSON DECODE数组解析样本值问题

问题描述 投票:0回答:3

我正在尝试输入json字符串:http://prntscr.com/kt8i8a

{"0":168,"1":168}

{"168":1,"168":2}

{"168":70000,"168":80000}

我的目的是得到2个id = 168的值,当我使用json_decode('{"168":1,"168":2}',true)时保存在DB中我得到的结果只有值:

array:1 [
  168 => 2
]

解析完整值的方法有多少?谢谢

php arrays json laravel parsing
3个回答
-2
投票

这不是一个有效的json语法,请尝试修复它。

如果你不能,因为你不能影响api,因为你没有开发它,你可以试试这样的正则表达式解析:

<?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
}
?>

4
投票

对象/词典中的键是唯一的,因此最后一个键的值将是final,并在此之前替换所有其他值。

两个解决方案,要么在数组中放置2个对象:

[
    {
        "168": "1"
    },
    {
        "168": "2"
    }
]

或者有一个168键的对象有2个值:

{
    "168": [
        "1",
        "2"
    ]
}

1
投票

在您的情况下,我希望您可以修改编码的json的格式,添加一些额外的信息,使其成为一个多维数组。有不同的方法可以使用不同的值来获得相同的键索引,其中一种可能是这样的:

{"data":
  [
    {"168":"1"},{"168":"2"}
  ]
}

在这种情况下,您可以获得所需的结果并访问值,否则不可能像在您的代码中那样,因为您有一个重复的唯一键索引。希望是明确的,并帮助你。

© www.soinside.com 2019 - 2024. All rights reserved.