php - 如何找到键值对数组的下一个键
问题描述
在我的预处理函数中,我有当前节点 id,以及一个包含所有节点 id 的数组,用于名为 recipes 的内容类型:
$current_node_id = \Drupal::routeMatch()->getParameter('node');
$nids = \Drupal::entityQuery('node')->condition('type','recipes')->execute();
$recipes_id = \Drupal\node\Entity\Node::loadMultiple($nids);
图中$recipes_id的结果如下:
接下来,我想遍历所有的 id 并获取与当前 id 相等的 ID:
$i = 0;
foreach($recipes_id as $key => $value) {
if($key == $current_node_id->id()) {
}
$i++;
}
在 if 语句中,我想访问 $key 变量之后的 id。所以如果当前 id 是 150,我应该访问 159,等等。为此,在 if 语句中我添加了以下内容:
$variables['node'] = $recipes_id[$i];
但是,当我查看该页面时,我看到一个空值:
{{ kint(node) }}
这是我的整个功能:
function amarula_preprocess_page(&$variables) {
/**
* get current node id
*/
$current_node_id = \Drupal::routeMatch()->getParameter('node');
/**
* check the current language
*/
$current_lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
$variables['current_lang'] = $current_lang; //current language code
/**
* get all recipes node id
*/
$nids = \Drupal::entityQuery('node')->condition('type','recipes')->execute();
$recipes_id = \Drupal\node\Entity\Node::loadMultiple($nids);
$variables['recipes_id'] = $recipes_id; // recipes node ID
$i = 0;
foreach($recipes_id as $key => $value)
{
if($key == $current_node_id->id())
{
$variables['node'] = $recipes_id[$i + 1];
break;
}
$i++;
}
}
拥有当前 ID,如何在数组中找到之后的 ID?
解决方案
这里是你如何获得下一把钥匙。
$keys = array_keys($recipes_id);
$i = 0;
foreach($keys as $value)
{
if($value == $current_node_id->id()){
$variables['node'] = $keys[$i + 1];
break;
}
$i++;
}
推荐阅读
- ios - 我们可以将图像添加到静态“框架”中吗?
- azure - 是什么导致 Azure Web 应用程序上的 Kudu cpu 高?
- mysql - 连接两个具有相同键但不同字段的表
- php - Laravel - 删除具有相同签名日期时间的几个模型
- java - 如何在 Java N-IDE 控制台应用程序中获取 Android 上下文?
- ios - SwiftUI • 如何实现半屏ShareSheet?
- shell - 将字符串格式化为在 shell posix 脚本中具有相同数量的字符
- c++ - 有没有办法将符号名称转换为函数名称?
- r - Extract string within first two quotation marks using regular expressions?
- reactjs - 是否有可能让 SVG 与 react-top-print 一起工作?