PHP按时间顺序将存储数组中的值设置为嵌套的foreach循环
我有一个PHP按时间顺序将存储数组中的值设置为嵌套的foreach循环,php,Php,我有一个$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.', 'B
$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();
}
}
}
但事实是:
$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.
如果要将
标题设置为键
$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));
参考资料
我认为这是因为您重写了循环中的值,然后它保存了数组的最后一个索引。如果可能,请粘贴您的预期输出。您是否尝试将Ludo Bagman
的内容设置为$key
0
和Bathilda Bagshot
设置为1
等?您应该澄清您的问题,不清楚您试图实现什么更新了问题的更多信息,现在应该有意义了。您的解决方案有意义,但在我尝试后,显示了以下错误:[warning]array_combine():两个参数的元素数应该相等
@rishikulshreshta Yes,对于每个元素$data
,您都需要在$keys
中输入一个键。这是一个完美的答案!数据最初在我的位置有点不正确,因此得到了错误。谢谢你的提醒。
$keyedNames = array_combine($keys, array_keys($data));