Home > Enterprise >  Printing a foreach loop in a loop maintaining json
Printing a foreach loop in a loop maintaining json

Time:10-06

I have this code as I am trying to implement a json code using foreach loop

foreach ($single_google as $row) {
    $data['step'][] = array(
        "@type" => "HowToStep",
        "url" => "https://example.com/kitchen#step1",
        "name" => "Prepare the surfaces",
        "itemListElement" => array(),
        "image" => [
            "@type" => "ImageObject",
            "url" => "https://example.com/photos/1x1/photo-step1.jpg",
            "height" => "406",
            "width" => "305"
        ],
    );


    $all_step_google = json_decode($row["steps"]);
    foreach ($all_step_google as $single_step_google) {
        $data['itemListElement'][] = array(
            "@type" => "HowToDirection",
            "text" => "testing",

        );
    }
}

print_r(json_encode($data));

at the end of the coding, trying to run it I got this

 {
      "@type": "HowToStep",
      "url": "https://example.com/kitchen#step1",
      "name": "Prepare the surfaces",
      "itemListElement": [],
      "image": {
        "@type": "ImageObject",
        "url": "https://example.com/photos/1x1/photo-step1.jpg",
        "height": "406",
        "width": "305"
      }
    }
  ],
  "itemListElement": [
    {
      "@type": "HowToDirection",
      "text": "test."
    }

instead of this which I needed actually.

 {
      "@type": "HowToStep",
      "url": "https://example.com/kitchen#step1",
      "name": "Prepare the surfaces",
      "itemListElement": [
    {
      "@type": "HowToDirection",
      "text": "Test"
    }
],
      "image": {
        "@type": "ImageObject",
        "url": "https://example.com/photos/1x1/photo-step1.jpg",
        "height": "406",
        "width": "305"
      }
    }
  ],

I want the "itemListElement" => array(), to print before the "image" => [] but it kept printing after the foreach loop. Please help me, am getting lost.

CodePudding user response:

You use $data['itemListElement'][] = array(... on your second loop so that will assign new key to your data master array instead, the right code should be like this

............
    foreach ($all_step_google as $key => $single_step_google) {
       $data['step'][$key]['itemListElement'][] = array(
          "@type" => "HowToDirection",
          "text" => "testing",
       );
    }
............
  • Related