2014-02-12 70 views
0

我無法讓in_array工作。它這是在我已經包含了一個文件中定義,然後調用從原始文件中的函數的函數中運行...這是越來越太複雜了,我會添加代碼:

index.php

$results = $database->get_results($query); 
foreach ($results as $question) { 
    echo '<div class="'.addQuestionClass($question).'"></div>'; 
} 

functions.php

$sectionConfig = array(
    'amount' => '20', 
    'types' => array('textarea', 'text', 'select', 'number'), 
); 

function addQuestionClass($question) { 
    if(is_array($question)) { 
     $order = 'order-'.$question['order']; 
     $id = ' question-'.$question['id']; 

     if(in_array($question['answer'], $sectionConfig['types'])) { 
      $answertype = ' type-'.$question['answer']; 
      echo 'true'; 
     } else { 
      $answertype = null; 
      echo 'false'; 
     } 

     return $answertype; 
    } else { 
     return; 
    } 
} 

問題的代碼是在我的addClass功能:

in_array($question['answer'], $sectionConfig['types'])

如果我運行相同的代碼,從$ sectionConfig粘貼的,像下面的陣列,它工作正常,但它從來沒有認識到我上面格式。

這個工程:

in_array($question['answer'], array('textarea', 'text', 'select', 'number'))

+2

你的函數'addQuestionClass'有'$ sectionConfig'陣列根本無法訪問。如果它甚至不能讀取這些值,它如何工作? –

回答

3

您正在訪問$sectionConfig自己的函數中。默認情況下,這是另一個作用域,並且函數中的代碼不知道$sectionConfig存在。

你可以嘗試這樣的事情:

$sectionConfig = array(
    'amount' => '20', 
    'types' => array('textarea', 'text', 'select', 'number'), 
); 

$results = $database->get_results($query); 
foreach ($results as $question) { 
    echo '<div class="'.addQuestionClass($question,$sectionConfig).'"></div>'; 
} 

function addQuestionClass($question,$sectionConfig) { 
    if(is_array($question)) { 
     $order = 'order-'.$question['order']; 
     $id = ' question-'.$question['id']; 

     if(in_array($question['answer'], $sectionConfig['types'])) { 
      $answertype = ' type-'.$question['answer']; 
      echo 'true'; 
     } else { 
      $answertype = null; 
      echo 'false'; 
     } 

     return $answertype; 
    } else { 
     return; 
    } 
} 
+0

我覺得自己像個白癡,有這麼多問題,謝謝 – user2992596

1

問題是,您的變量$sectionConfig是不是在你的函數的範圍。你可以使用global得到它的功能範圍或把它作爲一個變量:

function addQuestionClass($question) { 
    global $sectionConfig; // This gets your variable in the right scope. 
    if(is_array($question)) { 
     $order = 'order-'.$question['order']; 
     $id = ' question-'.$question['id']; 

     if(in_array($question['answer'], $sectionConfig['types'])) { 
      $answertype = ' type-'.$question['answer']; 
      echo 'true'; 
     } else { 
      $answertype = null; 
      echo 'false'; 
     } 

     return $answertype; 
    } else { 
     return; 
    } 
} 
+0

有關更多信息,最好不要使用'global',請參閱[本答案](http://stackoverflow.com/a/12446305/590877)。相反,只需在我的答案中傳遞數組。 – trizz