1

i have a json array, and i want to decode it to make it readable, but i always get an error. I want the output to be like this.

image1 image2 image3

$json = '

{
    "acf" : {
        "hero_banner" : [
            {
                "banner_image" : "image1",
                "banner_title" : "title1",
                "banner_desc" : "desc1"
            },
            {
                "banner_image" : "image2",
                "banner_title" : "title2",
                "banner_desc" : "desc2"
            },
            {
                "banner_image" : "image3",
                "banner_title" : "title3",
                "banner_desc" : "desc3"
            }

        ]
    }
}


';

$encode = json_encode($json,true);

$decode = json_decode($encode,true);

foreach ($decode as $key) {
     var_dump($key['acf']['hero_banner']);
}
nikko
  • 109
  • 1
  • 11

2 Answers2

1

This will echo them out and add to array. I wanted to show you another option :)

$arr = json_decode($json,true);
$banners = array();
$num = count($arr["acf"]["hero_banner"]); 
for($x = 0; $x < $num; $x++){
 echo $img = $arr["acf"]["hero_banner"][$x]["banner_image"] . " "; 
 $banners[] = $img; 
}
print_r($banners);
Nerdi.org
  • 895
  • 6
  • 13
0

Directly access the target subarray using the known keys. Then call array_column() to isolate the banner_image data from each subset. Finally implode the columnar data using a space as glue. Done.

Code: (Demo)

$decode = json_decode($json, true);
echo implode(' ', array_column($decode['acf']['hero_banner'], 'banner_image'));

Output:

image1 image2 image3

This task is EXACTLY why array_column() was implemented in php since version 5.5.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136