首页 > 解决方案 > 如何找到键值对数组的下一个键

问题描述

在我的预处理函数中,我有当前节点 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?

标签: phparraysdrupal-8

解决方案


这里是你如何获得下一把钥匙。

$keys = array_keys($recipes_id);
$i = 0;
foreach($keys as $value)
{
    if($value == $current_node_id->id()){
        $variables['node'] = $keys[$i + 1];
        break;
    }
    $i++;
}

推荐阅读