我有一个$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.
慕桂英4014372