PHP 按时间顺序将存储数组中的值设置为嵌套 foreach 循环

我有一个$data包含 4 个索引的数组。我在这里试图实现的是将$data数组中的值设置为嵌套foreach循环,但在执行结束时它存储最后一个索引的值。


<?php

// Some IDs.

$nids = [12, 56, 55, 59, 83];


$data = [

  'Ludo Bagman' => 'Head of the Department of Magical Games and Sports within the Ministry of Magic.',

  'Bathilda Bagshot' => 'Author of A History of Magic, and the great aunt of Gellert Grindelwald.',

  'Katie Bell' => 'Gryffindor Quidditch Chaser one year above Harry Potter. Member of Dumbledore\'s Army.',

  'Cuthbert Binns' => 'Ghost, History of Magic professor.',

];


foreach ($nids as $nid) {

  $term = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

  $paragraphs = $term->get('field_paragraphs')->referencedEntities();


  foreach ($paragraphs as $key => $paragraph) {


    if (in_array($key, [0, 1, 3, 6])) {


      // Here, only the last element from the $data array is stored, i.e. value

      // of `Cuthbert Binns`, whereas each of the above `$key` should take the

      // value from the `$data` array in chronological order.

      foreach ($data as $title) {

        $paragraph->get('field_links')->setValue([

          'title' => $title,

        ]);

      }

      $paragraph->save();

    }

  }

}

在上面的代码中,我尝试只循环到 4 $paragraph,它们中的每一个都应该具有诸如以下的值:


$paragraph[0]['field_links']['title']; // Head of the Department of Magical Games and Sports within the Ministry of Magic.

$paragraph[1]['field_links']['title']; // Author of A History of Magic, and the great aunt of Gellert Grindelwald.

$paragraph[3]['field_links']['title']; // Gryffindor Quidditch Chaser one year above Harry Potter. Member of Dumbledore\'s Army.

$paragraph[6]['field_links']['title']; // Ghost, History of Magic professor.

但它是:


$paragraph[0]['field_links']['title']; // Ghost, History of Magic professor.

$paragraph[1]['field_links']['title']; // Ghost, History of Magic professor.

$paragraph[3]['field_links']['title']; // Ghost, History of Magic professor.

$paragraph[6]['field_links']['title']; // Ghost, History of Magic professor.


忽然笑
浏览 83回答 1
1回答

慕桂英4014372

如果您想将title设为keys.$data = [&nbsp; 'Ludo Bagman' => 'Head of the Department of Magical Games and Sports within the Ministry of Magic.',&nbsp; 'Bathilda Bagshot' => 'Author of A History of Magic, and the great aunt of Gellert Grindelwald.',&nbsp; 'Katie Bell' => 'Gryffindor Quidditch Chaser one year above Harry Potter. Member of Dumbledore\'s Army.',&nbsp; 'Cuthbert Binns' => 'Ghost, History of Magic professor.',];$keys = [0,1,3,6];$keyedData = array_combine($keys, $data);// ...foreach ($paragraphs as $key => $paragraph) {&nbsp; &nbsp; if (in_array($key, $keys)) {&nbsp; &nbsp; &nbsp; &nbsp; $paragraph->get('field_links')->setValue([&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'title' => $keyedData[$key],&nbsp; &nbsp; &nbsp; &nbsp; ]);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $paragraph->save();&nbsp; &nbsp; }}如果您将来需要这些名称:$keyedNames = array_combine($keys, array_keys($data));
打开App,查看更多内容
随时随地看视频慕课网APP