2012-01-17 15 views
27

Sto usando la funzione array_map nella mia applicazione php. Ho definito la funzione array_map come questa.Errore PHP. Perché "variabile indefinita" all'interno di array_map?

$ratingID = $this->db->insert_id(); 

    $rated_item_array = array_map(function ($a) { 
     return $a + array('RatingID' => $ratingID); 
    }, $rated_item_array); 

preavviso Php viene

A PHP Error was encountered 

Severity: Notice 

Message: Undefined variable: ratingID 

quando stampo il $ratingID. stampo il valore correttamente, quindi $ ratingID è definito. Perché è indefinito nella funzione array_map? mio $rated_item_array è

Array 
(
    [0] => Array 
     (
      [RatingFactorPreferenceID] => 1, 
      [PreferenceID] => 45, 
      [RatedValue] => 1, 
      [CreatedOn] => 1326790338, 
      [CreatedBy] => 25 
     ) 

    [1] => Array 
     (
      [RatingFactorPreferenceID] => 2, 
      [PreferenceID] => 45, 
      [RatedValue] => 1, 
      [CreatedOn] => 1326790338, 
      [CreatedBy] => 25 
     ) 

    [2] => Array 
     (
      [RatingFactorPreferenceID] => 3, 
      [PreferenceID] => 45, 
      [RatedValue] => 1, 
      [CreatedOn] => 1326790338, 
      [CreatedBy] => 25 
     ) 
) 

risposta

73
$rated_item_array = array_map(
    function ($a) use ($ratingID){ 
    return $a + array('RatingID' => $ratingID); 
    }, 
    $rated_item_array 
); 
+0

funziona perfettamente. grazie mille –

+2

grazie per la bella risposta. –

+2

Dalla documentazione php.net sulle funzioni anonime. "Le chiusure possono anche ereditare variabili dall'ambito genitore. Qualsiasi di queste variabili deve essere passata al costrutto del linguaggio d'uso." Guarda l'esempio # 3 http://php.net/manual/en/functions.anonymous.php –