【问题标题】:how to get next value of array in PHP如何在PHP中获取数组的下一个值
【发布时间】:2019-02-13 23:12:31
【问题描述】:

我想当用户输入一个数字时,如果数字在数据库中,从数组中获取下一个值
我想从数组中的当前值获取下一个值,但是这段代码排在数组的前面

    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'];

            } 
        }

【问题讨论】:

  • 您是否在循环中运行此代码?循环遍历一个数组?
  • 是的,但它获取数组值的第一个
  • 请把你的完整代码,或者至少提供外循环
  • @linaa - 我的回答对你有帮助吗?你是这个意思吗?

标签: php arrays mysqli


【解决方案1】:

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

改变这个:

$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"];

【讨论】:

    【解决方案2】:

    这不是循环 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 var 没有定义)

    【讨论】:

    • mysqli 更好;)
    • 我认为$data是一个不同的数组,当sql返回数据时,用户需要在这个$data数组中进行迭代。
    猜你喜欢
    • 2021-09-26
    • 2018-03-03
    • 2014-03-03
    • 2019-02-11
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多