2014-06-13 48 views
0

我有一個數組,看起來像這樣,那我通過循環: 數組的名稱爲$測試非法失調誤差

Array 
(
[ven1] => Array 
    (
     [0] => Array 
      (
       [0] => ven1-center1 
       [1] => ven1 
       [2] => Address 
      ) 

     [1] => Array 
      (
       [0] => ven1-center2 
       [1] => ven1 
       [2] => Address 
      ) 

     [2] => Array 
      (
       [0] => ven1-center3 
       [1] => ven1 
       [2] => Address 
      ) 

      . 
      . 
      . 


[ven2] => Array 
    (
     [20] => Array 
      (
       [0] => ven2-center1 
       [1] => ven2 
       [2] => Address 
      ) 

     [21] => Array 
      (
       [0] => ven2-center2 
       [1] => ven2 
       [2] => Address 
      ) 

     [22] => Array 
      (
       [0] => ven2-center3 
       [1] => ven2 
       [2] => Address 
      ) 

下面我有循環整個數組的PHP代碼,從最內層獲取[0]的所有值,並將它們存儲到名爲$ k的數組中。 當我運行下面的代碼時,我得到Notice: Undefined offset:所有$ c的值。

for($c = 0; $c < 42; $c++){ 
     foreach($test as $k => $v){ 
      if($test[$k][$c][1] == $k){ 
      $k = $test[$k][$c][0]; 
     } 
     } 
    } 

輸出在找的是

$ven1 = array("ven1-center1","ven1-center2","ven1-center3","ven1-center4") 
$ven2 = array("ven1-center1","ven1-center2","ven1-center3","ven1-center4") 
+0

創建類似編號的變量是幾乎總是錯的。使用數組。 – Barmar

+0

@Barmar你能解釋一下你的意思嗎? – hello

+1

而不是'$ ven1'和'$ ven2',你應該有一個'$ ven'數組,其中'$ ven ['ven1'] = array(「ven1-center1」,「ven1-center2」,「ven1-中心3「,」ven1-center4「)和'$ ven ['ven2'] =陣列(」ven1-center1「,」ven1-center2「,」ven1-center3「,」ven1-center4「)。 – Barmar

回答

1

我認爲這會做你想要什麼......假設我正確地解釋你的問題:

foreach($test as $varname => $array){ 
    foreach($array as $row) { 
     if ($row[1] == $varname) ${$varname}[] = $row[0]; 
    } 
} 

var_dump($ven1); 
var_dump($ven2); 
+0

$ ven1和$ ven2都完全回聲。當我'print_r($ {$ varname})''我沒有得到一個$ ven1和$ ven2的數組。這是正常的嗎?也可以是什麼符號是'$ {$ varname}'? 謝謝 – hello

+1

它被稱爲_variable variable_。 http://us3.php.net//manual/en/language.variables.variable.php – Barmar

+1

'$ {$ varname} []'表示採用名稱爲'$ varname'的變量 - 所以在這種情況下''$ varname'包含'「ven1」',所以我們將變量'$ ven1'。通常你可以做'$$ varname',但由於它是一個數組,所以我們必須使用'{}',因爲如果'[]'引用'$ varname'或'$$ varname',它就不明確。 – dave