简体   繁体   中英

PHP Array & Pointer Confusion

Let's say I have a function like this:

function z($zzz){
   for($c=0;$c<5;$c++){
   $zzz[$c]= 10;  
   //more and more codes
   }    
}

I want to write a loop so that

the 1st time the function is executed, argument $array is passed

the 2nd time : argument $array[0] is passed

while the 3rd time : argument $array[1] is passed

.....

and the 12th time : argument $array[0][0] is passed

This is what comes to my mind:

$a = -1;
$b = -1;
$array = array();

while($a<10){
    while($b<10){
         z($array);
         $b++;
         $array= &$array[$b];
    }
    $a++;
    $array= &$array[$a];  
}

I've tried it but it didn't work..

I would appreciate if someone can provide a solution..

如果z()应该更改传递的数组,则函数定义应为:

function z(&$zzz)
$a = 0;
while ($a < 99)         // <-- edit as applicable
{
   $b = 0
   while ($b < 12)
   {
      if ($b == 0)
      {
         Z($array[$a]);
      } else
      {
         Z($array[$a][$b]);
      }
     $b++;
   }
   $a++;
}

And as stated by Jack you need to pass the $array variable by reference for update. Not too sure what that function is trying to achieve though. If you need to fill an array with a predermined dimension, maybe array_fill could be more useful.

http://www.php.net/manual/en/function.array-fill.php

function z(&$zzz){
   for($c=0;$c<5;$c++){
      $zzz[$c]= 10;  
      //more and more codes
   }    
}

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