如何在PHP中获取数组的下一个值

时间:2018-09-09 07:08:03

标签: php arrays mysqli

我想在用户输入数字时,如果数字在数据库中,请从数组中获取下一个值
我想从数组中的当前值中获取下一个值,但是此代码首先进入数组

    if ($value['number'] == $number) {

            $result = mysqli_query( $con,"SELECT user_name FROM tbl_users WHERE  user_name ='".$value['name']."'" );
            if ($result && mysqli_num_rows($result) > 0) {

                $iter = new \ArrayIterator($data);
                $iter->next();
                $nextKey = $iter->key();
                $nextValue = $iter->current();
                $user_id = $value['number'];
                $user_name = $value['name'];

            } 
        }

2 个答案:

答案 0 :(得分:1)

这不是循环mysqli结果(php documantation)的方法。您应该尝试这种方式:

while ($row = mysqli_fetch($result)) {
   $user_id = $row['number'];
   $user_name = $row['name'];
   // do what ever you need with those value
}

(而且,您在问题中的$data变量未定义)

答案 1 :(得分:0)

我认为您的问题是迭代器,但您不需要

更改此:

$iter = new \ArrayIterator($data);
$iter->next();
$nextKey = $iter->key();
$nextValue = $iter->current();
$user_id = $value['number'];
$user_name = $value['name'];

为此:

/* This will return an array with "key" and "value" items and advance the array curson one item */
$nextValue = each($data); 
print $nextValue["key"];
print $nextvalue["value"];