如何找到键值对数组的下一个键
How do I find the next key of a key value pair array
在我的预处理函数中,我有当前节点 ID,以及一个包含名为 recipes 的内容类型的所有节点 ID 的数组:
$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++;
}
在我的预处理函数中,我有当前节点 ID,以及一个包含名为 recipes 的内容类型的所有节点 ID 的数组:
$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++;
}