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

时间:2015-03-06 01:58:15

标签: php arrays json

我在PHP中使用json_decode来解码一个JSON对象,该对象可能有1d数组或2d数组的值:

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

{"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=="}]}

我使用$ Cell = $ json [" Cell"]来访问元素。我面临的问题是第二种情况很好,我得到一个数组数组,而第一种应该是单个元素数组,但被解释为3元素数组。

1 个答案:

答案 0 :(得分:0)

你不能检查元素是否有密钥吗?像这样:

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