php数组在for循环中给出错误

问题描述:

i am trying to add loop, but i am getting error...i tried to clear the array before every loop but won't work for me.

<?php

for ($aw = 1; $aw <= 49; $aw++) {

    $cart = array("orange", "banana");

    $result = array(); 
    $combination = array();

    function combinations(array $myArray, $choose) {
        global $result, $combination;

        $n = count($myArray);
        function inner ($start, $choose_, $arr, $n) {
            global $result, $combination;

            if ($choose_ == 0) array_push($result,$combination);
            else for ($i = $start; $i <= $n - $choose_; ++$i) {
                array_push($combination, $arr[$i]);
                inner($i + 1, $choose_ - 1, $arr, $n);
                array_pop($combination);
            }
        }
        inner(0, $choose, $myArray, $n);
        return $result;
    }
    $array=combinations($cart, 6); // this is your 2d array

    $counnumber=1;
    foreach ($array as $row) {
        $counnumber++;
    }
    echo $counnumber;
}

i am getting following error

Fatal error: Cannot redeclare combinations() (previously declared in    
/home/www/mywebsite.com/checkingerror.php:11) in 
/home/www/mywebsite.com/checkingerror.php on line 11

please check the following code, and help me!

thanks

You are declaring combinations function inside a loop. Move it outside the loop.

function combinations(array $myArray, $choose) {
global $result, $combination;

 $n = count($myArray);
 function inner ($start, $choose_, $arr, $n) {
   global $result, $combination;

    if ($choose_ == 0) array_push($result,$combination);
    else for ($i = $start; $i <= $n - $choose_; ++$i) {
       array_push($combination, $arr[$i]);
       inner($i + 1, $choose_ - 1, $arr, $n);
       array_pop($combination);
       }
  }
  inner(0, $choose, $myArray, $n);
  return $result;
}

for ($aw = 1; $aw <= 49; $aw++) {
...

Look at the error, when you call the loop the first time, you declare the function.

After that, every time in the loop you are redefining the same function => error

// function declaration here
// you can call the function inside the loop here