How do I find the next key of a key value pair array

user agent :

In my preprocess function, I have the current node id, and an array with all node ids for a content type called recipes:

$current_node_id = \Drupal::routeMatch()->getParameter('node');
$nids = \Drupal::entityQuery('node')->condition('type','recipes')->execute();
$recipes_id =  \Drupal\node\Entity\Node::loadMultiple($nids);

The result of $recipes_id is as follows in the picture:

enter image description here

Next, I want to loop through all the ids and get the ID that is equal to the current id:

 $i = 0;
 foreach($recipes_id as $key => $value) {
    if($key == $current_node_id->id()) {

    }
    $i++;
 }

In the if statement, I want to access the id that is after the $key variable. so if the current id is 150 I should access 159, etc. For that, inside the if statement I added the following:

$variables['node'] = $recipes_id[$i];

When I view the page though, I see a null:

{{ kint(node) }}

Here is my entire function:

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++;
    }
}

Having the current ID, how can I find the ID after that in the array?

Omar Abbas :

here is how you get the next key.

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=293888&siteId=1
Recommended