PHP count JSON array

故事扮演 提交于 2019-11-27 06:53:57

问题


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

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);

And echo count prints out '1' not '3'.


回答1:


Try echo count($task_array['task']);

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>

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.




回答2:


$task_array = json_decode($json_tasks);
count($task_array->task);

EX: 3

From Taiwan




回答3:


Well the 3 items are in 1 item "task" so, you have one array named task and the 3 elements are in it

try

echo count($task_array['task']);

EDIT :

please use the below code to print the array in correct pattern

echo '<pre>';
print_r($task_array['task']);
exit();



回答4:


try this code, here i can able to count the number of objects with specific value

here's my data.json file content

{"likes":[
    {"user_id":1,"time":"12:04pm"},
    {"user_id":2,"time":"02:04pm"},
    {"user_id":67,"time":"11:04pm"},
    {"user_id":1,"time":"12:04pm"}
]}

here's the php code

<?php
$jsonData = file_get_contents("data.json");
$data = json_decode($jsonData,true);
$total = 0;
foreach ($data["likes"] as $value) {
    if($value["user_id"]==1){
        $total = $total+1;
    }
}
echo $total;
?>

output will be

2


来源:https://stackoverflow.com/questions/19606094/php-count-json-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!