简体   繁体   中英

PHP Go to the next element of array

I have created an array list with the following code:

<?php

$ids = array();

if (mysql_num_rows($query1))
{
    while ($result = mysql_fetch_assoc($query1))
    {
        $ids["{$result['user_id']}"] = $result;
    }
}
mysql_free_result($query1);

?>

Now, i need to read two elements from the array. The first is the current and the second one is the next element of array. So, the simplified process is the following:

i=0: current_element (pos:0), next_element (pos:1)
i=1: current_element (pos:1), next_element (pos:2)
etc

To do this, i have already written the following code, but i cant get the next element for each loop!

Here is the code:

if (count($ids)) 
{ 
    foreach ($ids AS $id => $data) 
    { 
        $userA=$data['user_id'];
        $userB=next($data['user_id']);
    }
}

The message i receive is: Warning: next() expects parameter 1 to be array, string given in array.php on line X

Does anyone can help? Maybe i try to do it wrongly.

The current , next , prev , end functions work with the array itself and place a position mark on the array. If you want to use the next function, perhaps this is the code:

if (is_array($ids)) 
{ 
    while(next($ids) !== FALSE) // make sure you still got a next element
    {
        prev($ids);             // move flag back because invoking 'next()' above moved the flag forward
        $userA = current($ids); // store the current element
        next($ids);             // move flag to next element
        $userB = current($ids); // store the current element
        echo('  userA='.$userA['user_id']);
        echo('; userB='.$userB['user_id']);
        echo("<br/>");
    }
}

You'll get this text on the screen:

userA=1; userB=2
userA=2; userB=3
userA=3; userB=4
userA=4; userB=5
userA=5; userB=6
userA=6; userB=7
userA=7; userB=8

You get the first item, then loop over the rest and at the end of each loop you move the current item as the next first item ... the code should explain it better:

if (false !== ($userA = current($ids))) {
    while (false !== ($userB = next($ids))) {
        // do stuff with $userA['user_id'] and $userB['user_id']
        $userA = $userB;
    }
}

Previous answer

You can chunk the arrays into pairs:

foreach (array_chunk($ids, 2) as $pair) {
    $userA = $pair[0]['user_id']
    $userB = $pair[1]['user_id']; // may not exist if $ids size is uneven
}

See also: array_chunk()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM