I'm not sure if you want to do this in JavaScript or PHP since you have an array in JavaScript format. If it's a JSON you need to use json_decode
in PHP.
JavaScript:
var arr = [[],[{"id":3,"image_name":"47440_planet_mars.jpg","path":"59c1d5ddd862547440_planet_mars.jpg","imageable_id":9,"imageable_type":"App\Assay","created_at":"2017-09-20 02:43:41","updated_at":"2017-09-20 02:43:41"}],[],[],[],[{"id":5,"image_name":"50066_space_mission_space_shuttle_before_launch.jpg","path":"59c1d5de36aa950066_space_mission_space_shuttle_before_launch.jpg","imageable_id":2,"imageable_type":"App\Assay","created_at":"2017-09-20 02:43:42","updated_at":"2017-09-20 02:43:42"},{"id":4,"image_name":"48542_space_mission_iss.jpg","path":"59c1d5ddd904048542_space_mission_iss.jpg","imageable_id":2,"imageable_type":"App\Assay","created_at":"2017-09-20 02:43:41","updated_at":"2017-09-20 02:43:41"},{"id":2,"image_name":"oh5Ef7w.jpg","path":"59c1d5dd91752oh5Ef7w.jpg","imageable_id":2,"imageable_type":"App\Assay","created_at":"2017-09-20 02:43:41","updated_at":"2017-09-20 02:43:41"},{"id":1,"image_name":"SGHRgHo.jpg","path":"59c1d5dd8f85aSGHRgHo.jpg","imageable_id":2,"imageable_type":"App\Assay","created_at":"2017-09-20 02:43:41","updated_at":"2017-09-20 02:43:41"}]];
var resultado = arr.map(el => el.length);
console.log(resultado);
PHP
In PHP, you need to match json_decode
with array_map
and count
, the native function to know the number of elements in an array.
Ficaria assim:
$string = '
[
[],
[
{
"id": 3,
"image_name": "47440_planet_mars.jpg",
"path": "59c1d5ddd862547440_planet_mars.jpg",
"imageable_id": 9,
"imageable_type": "AppAssay",
"created_at": "2017-09-20 02:43:41",
"updated_at": "2017-09-20 02:43:41"
}
],
[],
[],
[],
[
{
"id": 5,
"image_name": "50066_space_mission_space_shuttle_before_launch.jpg",
"path": "59c1d5de36aa950066_space_mission_space_shuttle_before_launch.jpg",
"imageable_id": 2,
"imageable_type": "AppAssay",
"created_at": "2017-09-20 02:43:42",
"updated_at": "2017-09-20 02:43:42"
},
{
"id": 4,
"image_name": "48542_space_mission_iss.jpg",
"path": "59c1d5ddd904048542_space_mission_iss.jpg",
"imageable_id": 2,
"imageable_type": "AppAssay",
"created_at": "2017-09-20 02:43:41",
"updated_at": "2017-09-20 02:43:41"
},
{
"id": 2,
"image_name": "oh5Ef7w.jpg",
"path": "59c1d5dd91752oh5Ef7w.jpg",
"imageable_id": 2,
"imageable_type": "AppAssay",
"created_at": "2017-09-20 02:43:41",
"updated_at": "2017-09-20 02:43:41"
},
{
"id": 1,
"image_name": "SGHRgHo.jpg",
"path": "59c1d5dd8f85aSGHRgHo.jpg",
"imageable_id": 2,
"imageable_type": "AppAssay",
"created_at": "2017-09-20 02:43:41",
"updated_at": "2017-09-20 02:43:41"
}
]
]
';
$arr = json_decode($string, TRUE);
$resultado = array_map("count", $arr);
var_dump($resultado); // array(6) { [0]=> int(0) [1]=> int(1) [2]=> int(0) [3]=> int(0) [4]=> int(0) [5]=> int(4) }
Note: In PHP I think App\Assay
has invalid characters, I'm not sure where this JSON comes from, so I took the example.