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\",
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.
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();
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
$task_array = json_decode($json_tasks);
count($task_array->task);
EX: 3
From Taiwan