【问题标题】:PHP Go to the next element of arrayPHP 转到数组的下一个元素
【发布时间】:2012-11-28 13:18:22
【问题描述】:

我用以下代码创建了一个数组列表:

<?php

$ids = array();

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

?>

现在,我需要从数组中读取两个元素。第一个是当前元素,第二个是数组的下一个元素。因此,简化的过程如下:

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

为此,我已经编写了以下代码,但是我无法获取每个循环的下一个元素!

代码如下:

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

我收到的消息是:警告:next() 期望参数 1 是数组,在第 X 行的 array.php 中给出的字符串

有人可以帮忙吗?也许我尝试做错了。

【问题讨论】:

    标签: php arrays arraylist


    【解决方案1】:

    currentnextprevend 函数使用数组本身并在数组上放置位置标记。如果你想使用next 函数,也许代码如下:

    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/>");
        }
    }
    

    你会在屏幕上看到这个文本:

    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
    

    【讨论】:

      【解决方案2】:

      你得到第一个项目,然后循环其余部分,在每个循环结束时,你将当前项目移动为下一个第一个项目......代码应该更好地解释它:

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

      上一个答案

      您可以将数组分块成对:

      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
      }
      

      另请参阅:array_chunk()

      【讨论】:

      • 我使用 if ($last_item != $pair[1]) { 检查 $pair[1] 是否存在,然后执行操作。但是运行上面的代码,我收到这个错误:注意:数组到字符串的转换
      • @zuperakos 你应该使用 isset() 代替。
      • 谢谢!我用 if isset 替换 if 条件。但是您对我收到的通知(注意:数组到字符串的转换)有任何想法吗?当我使用 echo $userB 时,它出现了这个词:Array
      • 你检查我更新的答案了吗?我的初始版本缺少一些东西。
      • 是的,但是这段代码执行以下操作:A-B,C-D。我想这样做:A-B、B-C、C-D
      猜你喜欢
      • 1970-01-01
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多