简体   繁体   English

使用带有1d和2d数组的php json_decode

[英]Using php json_decode with 1d and 2d array

I am using json_decode in PHP to decode a JSON object which may have 1d array or 2d array for a value: 我在PHP中使用json_decode来解码一个JSON对象,该对象可能有1d数组或2d数组的值:

{"Cell":{"@column":"ZjE6dW5pdmVyc2l0eQ==","@timestamp":"1425598820484","$":"MC44MDc2NDEwNDg0MjI5MjMy"}}

or 要么

{"Cell":[{"@column":"ZjE6YQ==","@timestamp":"1425599309809","$":"MC4wNTYzMzgwMjgxNjkwMTQwODY="},{"@column":"ZjE6YW5k","@timestamp":"1425599309809","$":"MC4wNTYzMzgwMjgxNjkwMTQwODY="},{"@column":"ZjE6Y2F0Y2hlcw==","@timestamp":"1425599309809","$":"MC4wNDIyNTM1MjExMjY3NjA1Ng=="},{"@column":"ZjE6aQ==","@timestamp":"1425599309809","$":"MC4wOTg1OTE1NDkyOTU3NzQ2NA=="},{"@column":"ZjE6dGhhdA==","@timestamp":"1425599309809","$":"MC4xNjkwMTQwODQ1MDcwNDIyNQ=="}]}

and I am using $Cell = $json["Cell"] to access the elements. 我正在使用$ Cell = $ json [“Cell”]来访问元素。 The problem I am facing is that the second case plays nicely and I get an array of arrays while the first one should be a single element array but is being interpreted as a 3 element array. 我面临的问题是第二种情况很好,我得到一个数组数组,而第一种应该是单个元素数组,但被解释为3元素数组。

Can't you just check if the element has the key? 你不能只检查元素是否有密钥? Like this: 像这样:

if (isset($json['Cell']['@column']) {
    // do stuff with single-element
} else {
    // it is a collection
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM