3

thanks for your time:

First of all I have the following Json string

$jsonarr = '["somestring1", "somestring2","somestring3"]'

which I want to convert to a PHP array

$decodedjson = json_decode($jsonarr,TRUE);

and then iterate through all of the members of the array, something such as :

for ($i=0;$i<3;$i++)
{
    echo $decodedjson[$i];
}

First of all, is it possible to get the length of this array?

Second, this code throws an error. I am not sure where I am doing it wrong.

Thank you for your time.

4

4 回答 4

1

我看到的唯一错误是第一行缺少分号。你可以得到这样的长度:

count($decodedjson);
于 2013-10-25T21:01:36.710 回答
1

是的,您可以通过如下函数获取数组长度count()

$jsonarr = '["somestring1", "somestring2","somestring3"]' ;
$decodedjson = json_decode($jsonarr);

for ($i=0;$i < count($decodedjson);$i++) 
{
    echo $decodedjson[$i] . '<br>';
}
于 2013-10-25T21:03:27.287 回答
1

如果 json_decode() 返回的数组是有效的,是的。你只需要打电话:

 count($decodedjson);

但首先,尝试做一个 $decodedjson 的 var_dump。你会看到它是如何被解码的。如果它等于 null,则 json_decode() 调用失败。您可以使用 json_last_error() 获取错误代码(错误代码列表:http: //php.net/manual/en/function.json-last-error.php

如果你想更快,并且在不知道长度的情况下遍历数组,你只需要使用 foreach 而不是 for 循环。

是的,就像 Akshay 说的,分享你遇到的错误。祝你好运。

于 2013-10-25T21:03:42.087 回答
0

与往常一样,您可以使用它foreach来遍历对象/数组:

foreach ($decodedjson as $key => $value) {
    echo $key . ' => ' .$value;
}
于 2013-10-25T21:11:35.063 回答