为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
忽然笑 2023-09-22 17:47:49
我有一个$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.
查看完整描述

1 回答

?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

如果您想将title设为keys.


$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.',

];

$keys = [0,1,3,6];

$keyedData = array_combine($keys, $data);


// ...


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

    if (in_array($key, $keys)) {

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

          'title' => $keyedData[$key],

        ]);

        

        $paragraph->save();

    }

}

如果您将来需要这些名称:


$keyedNames = array_combine($keys, array_keys($data));


查看完整回答
反对 回复 2023-09-22
  • 1 回答
  • 0 关注
  • 52 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信