Home > Software engineering >  Get data from a sub-array with json and php
Get data from a sub-array with json and php

Time:12-05

I would like to obtain the value of "single_img" that is in a subarray but I can't find the way

$video ='{"msg":"OK","server_time":"2021-12-04 20:33:26","status":200,"result":[{"single_img":"8eybbqf5nnta6vcw.jpg","file_code":"vg1fkuag1tsa","splash_img":"8eybbqf5nnta6vcw.jpg","canplay":1,"views":"0","length":"2370","uploaded":"2021-12-04 13:28:35","title":"(Hands On Ed Class \/ 12.04.2021)"}]}';

$do = json_decode($video);

echo json_encode($do);
 
$result= json_encode($do->result);

echo json_encode($result->single_img);

I appreciate your answers

CodePudding user response:

you can decode the string as an associative array and access your key:

$video ='{"msg":"OK","server_time":"2021-12-04 20:33:26","status":200,"result":[{"single_img":"8eybbqf5nnta6vcw.jpg","file_code":"vg1fkuag1tsa","splash_img":"8eybbqf5nnta6vcw.jpg","canplay":1,"views":"0","length":"2370","uploaded":"2021-12-04 13:28:35","title":"(Hands On Ed Class \/ 12.04.2021)"}]}';

$do = json_decode($video, true);

var_dump($do['result'][0]['single_img']);

CodePudding user response:

This too will work just as fine:

$video = '{"msg":"OK","server_time":"2021-12-04 20:33:26","status":200,"result":[{"single_img":"8eybbqf5nnta6vcw.jpg","file_code":"vg1fkuag1tsa","splash_img":"8eybbqf5nnta6vcw.jpg","canplay":1,"views":"0","length":"2370","uploaded":"2021-12-04 13:28:35","title":"(Hands On Ed Class \/ 12.04.2021)"}]}';

$do = json_decode($video);
$result = $do->result;
echo json_encode($result[0]->single_img);
  • Related