flash
flash

Reputation: 1517

How to calculate the length of JSON values in php?

I have a JSON as shown below in which I want to calculate through php how many values are present inside posts_id_en. At present, it is 7 as shown below:

{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}

In php code on doing echo $data->{"posts_id_en"};, it displays the values as shown below:

149968, 149939, 149883, 149877, 149876, 149847, 154303

Problem Statement:

I am wondering what php code I need to use so that we can calculate number of values entered inside posts_id_en. At this moment, it is entered 7 as shown above.

Upvotes: 1

Views: 220

Answers (3)

Emma
Emma

Reputation: 27723

One simple way would be that we first json_decode, then validate numbers in our desired attribute, and count the matches:

$str = '{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}';

$str_array = json_decode($str, true);

preg_match_all('/(\d+)/s', $str_array["posts_id_en"], $matches);

echo sizeof($matches[0]);

Output

7

Upvotes: 1

Alo
Alo

Reputation: 160

The items you are trying to count are in a single string. First, you must break the string into items, then you can count them.

Take the json and make it into a php array

$jsonData = '{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}';
$data = json_decode($jsonData, true);

then split the string with the delimiter ", "

$items = explode(", ", $data['posts_id_en']);

then count

echo count($items);

Upvotes: 4

Jimmix
Jimmix

Reputation: 6506

<?php

$json = '{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}';
$decoded = json_decode($json, true);
$post_id = $decoded['posts_id_en'];

$resultList = [];
foreach($decoded as $key => $entry) {
    $everyNumberAsArray = explode(',', $entry);    
    $count = count($everyNumberAsArray);
    $resultList[$key] = $count;
}

var_export($resultList);

gives output:

array (
  'posts_id_en' => 7,
  'posts_id_fr' => 5,
  'episode_status' => 1,
)

to get particular values you use them this way:

echo $resultList['posts_id_en'] . '<br>' . PHP_EOL;

that gives you:

7

Upvotes: 1

Related Questions