如何找到键值对数组的下一个键

问题描述 投票:1回答:1

在我的预处理功能中,我具有当前节点ID,以及一个包含所有节点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的结果如下图所示:

enter image description here

接下来,我想遍历所有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之后的ID?

php arrays drupal-8
1个回答
1
投票

这里是获得下一个密钥的方式。

$keys = array_keys($recipes_id);
$i = 0;
foreach($keys as $value)
{
    if($value == $current_node_id->id()){
        $variables['node'] = $keys[$i + 1];
        break;
    }
    $i++;
}
© www.soinside.com 2019 - 2024. All rights reserved.