PHP count JSON array

2019-01-19 18:05发布

问题:

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:

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


回答3:

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

EX: 3

From Taiwan



回答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