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

时间:2013-08-02 01:12:49

标签: php arrays function

我正在尝试添加循环,但是我收到错误...我试图在每次循环之前清除数组但是对我不起作用。

<?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;
}

我收到以下错误

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

请检查以下代码,并帮助我!

感谢

2 个答案:

答案 0 :(得分:1)

您在循环中声明combinations函数。把它移到循环外面。

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++) {
...

答案 1 :(得分:1)

看看错误,当你第一次调用循环时,你声明了这个函数。

之后,每次在循环中重新定义相同的函数=&gt;的错误

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