Печать цикла foreach в цикле с сохранением json

#php #arrays #json #foreach #schema

Вопрос:

У меня есть этот код, так как я пытаюсь реализовать код json с помощью цикла foreach

 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));
 

в конце кодирования, пытаясь запустить его, я получил это

  {
      "@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."
    }
 

вместо того, что мне было нужно на самом деле.

  {
      "@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"
      }
    }
  ],
 

Я хочу, чтобы «Элемент списка элементов» => массив (),> печатался перед «изображением» = > []>, но он продолжал печатать после цикла foreach. Пожалуйста, помогите мне, я теряюсь.

Ответ №1:

Вы используете $data['itemListElement'][] = array(... во втором цикле, чтобы вместо этого назначить новый ключ вашему массиву данных, правильный код должен быть таким

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

Комментарии:

1. Я получил эту ошибку с незаконным типом смещения , используя $data[$single_step_google]['itemListElement'][] = array(...

2. Я обновил свой ответ