PHP计数JSON数组 [英] PHP count JSON array
问题描述
我搜索了SO但找不到答案。我的PHP脚本通过http post收到一些JSON,如下所示:
I have searched SO but couldn't find an answer.My PHP script is receiving some JSON by http post that looks like this:
{
"task": [
{
"task_id": "3",
"task_due": "Oct 26 11:25",
"task_completed": "FALSE",
"task_desc": "fff",
"task_time": "20131026_112531",
"task_name": "fff"
},
{
"task_id": "2",
"task_due": "Oct 26 11:25",
"task_completed": "FALSE",
"task_desc": "rff",
"task_time": "20131026_112522",
"task_name": "xff"
},
{
"task_id": "1",
"task_due": "Oct 26 11:25",
"task_completed": "FALSE",
"task_desc": "fggg",
"task_time": "20131026_112516",
"task_name": "ff"
}
]}
正如你所看到的,有3个项目,但当我把它变成一个PHP数组对象并计算项目时,我返回1,当它应该是3时,这是我的PHP代码:
As you can see, there are 3 items, but when I turn it into a PHP array object and count the items, I'm returned 1, when it should be 3, here is my PHP code:
$json_tasks = $_POST["json_array"];
$task_array = json_decode($json_tasks,true);
echo count($task_array);
和回显计数
打印出'1'不是'3'。
And echo count
prints out '1' not '3'.
推荐答案
尝试 echo count($ task_array ['task']);
一般来说,如果你想知道变量值 $ var
是,做一个
In general, if you wonder what the structure of the value of a variable $var
is, do a
<pre><?php var_export($var, true); ?></pre>
此功能优于序列化
和 print_r
是,它打印PHP代码(因此任何理解PHP的人都可以阅读(如果你用PHP编程的话)。) var_export
的缺点是,它无法处理循环结构(例如,如果 $ a-> b == $ a
),但JSON也不行。
Advantage of this function over alternatives such as serialize
and print_r
is, that it prints PHP code (and is thus readable by anyone who understands PHP (which is likely if you program in PHP)). Disadvantage of var_export
is, that it cannot handle circular structures (e.g. if $a->b == $a
), but neither can JSON.
这篇关于PHP计数JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!