将数组的指针设置为php中函数内数组的特定元素


Set pointer of array to specific element of array inside a function in php

我有一个数组,想要将指针设置为其中的特定元素(函数内部)

function arrowlink($side){
        reset($Arrowdata);
        $currentelement = '$_GET[food]';
        if ($side == 'left') {
            while (current($Arrowdata) !== $currentelement) {
            next($Arrowdata);
            }
    }

$Arrowdata如下所示:Array ( [0] => Apricots [1] => Asparagus [2] => Broccoli, raw [3] => Cabbage [4] => Carrots)

$_GET[food]是食品的名称

我总是收到这样的错误:警告:reset()要求参数1是数组,在中给定null
警告:current()要求参数1为数组,在中给定null。。。

它以一个无休止的循环结束。

我做错了什么?

我的猜测是,您在函数外部定义了$Arrowdata,这意味着$Arrowdata不存在于函数范围中。你可以这样解决:

$Arrowdata= array(1,2,3,4,5,6,7,8,9,10);
$side = 'left';
arrowlink($side, $Arrowdata);
function arrowlink($side, $Arrowdata){
        reset($Arrowdata);
        $currentelement = '$_GET[food]';
        if ($side == 'left') {
            while (current($Arrowdata) !== $currentelement) {
            next($Arrowdata);
        }
}

您没有定义数组。在您的代码中:

function arrowlink($side){
        reset($Arrowdata);
        $currentelement = '$_GET[food]';
        if ($side == 'left') {
            while (current($Arrowdata) !== $currentelement) {
            next($Arrowdata);
            }
    }

$ArrowData不是数组,除非您定义$ArrowData=array();作为一个数组。您还需要填充$ArrowData字段。不是结构正确。

如果数组是在函数之前定义的,并且您想访问它,则应该使用global关键字。此外,您还应该验证next函数返回的值(当数组中没有更多元素时,它会返回FALSE)。

function arrowlink($side){
    global $Arrowdata;
    reset($Arrowdata);
    $currentelement = $_GET[food]; // $_GET[food] is already a string !
    if ($side == 'left') {
        while (current($Arrowdata) !== $currentelement){
            if(next($Arrowdata) === FALSE)
                break;
        }
}

因为在我看来,还没有人能正确地确定他们的答案,所以这是我的答案。它修复了你犯的多个错误:

  1. 你不会把数组传递给函数——没有它它就无法工作
  2. 您必须通过引用将此数组传递给函数,否则函数将不会更改原始数组中的任何内容。我认为,使用global关键字既不是一个好主意,也不是一个首选主意
  3. 函数中应提供允许的$sides,以防止意外执行任何操作
  4. 在函数内部使用$_GET通常不是一个好的设计——将所需的$_GET值作为参数传递

这是代码:

$Arrowdata= array(1,2,3,4,5,6,7,8,9,10);
$side = 'left';
arrowlink($Arrowdata, $side, $_GET['food']);
//notice the passing by reference
function arrowlink(& $Arrowdata, $side, $currentelement){
   //put allowed sides here
   $allowedSides = array('left');
   //only allowed sides change arrays, others do not do anything
   if (!in_array($side, $allowedSides)) return;
   reset($Arrowdata);
   //$currentelement = '$_GET[food]';  // it is now passed to the function
   if ($side == 'left') {
      while (current($Arrowdata) !== $currentelement) {
         if (FALSE === next($Arrowdata)) {
            break;  //break if no next elements are there
         }
      }
   }
}