How to calculate the length of JSON values in php?
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);
<?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
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