2017-01-22 70 views
1

我有一個波紋管php whilefor循環。爲什麼我不能使用它的鍵來訪問數組元素?

while循環它存儲$ch_for數據在$ch_for數組。

使用print_r該陣列顯示這些值:

Array ([ch7] => Seven [ch8] => Eight) 

,並試圖利用此行訪問for循環這個array數據:

echo $ch_for["ch{$x}"]; 

但它顯示錯誤信息:非法字符串偏移'ch7'in ...

while和for循環結果的var_dump(array_keys($ch_for));

array(2) { 
    [0]=> 
    string(3) "ch7" 
    [1]=> 
    string(3) "ch8" 
} 
+0

你能'的var_dump(array_keys($ ch_for));'和後結果?您在其他分支中覆蓋'$ ch_for'。 – ccKep

回答

0

$ch_for  = array(); 
$ch_name = array(); 

while ($fetchChannel = mysqli_fetch_array($getChannel)) { 
    $ch_id  = (int) $fetchChannel['ch_id']; 
    $ch_for[$fetchChannel['ch_name']] = htmlspecialchars($fetchChannel['ch_for']); 
    $ch_name[] = htmlspecialchars($fetchChannel['ch_name']); 
} 


for ($x=1; $x<=12; $x++) { 
    if( in_array('ch'.$x, $ch_name)) { 
     $sel = 'checked = "checked" '; 
     echo $ch_for["ch{$x}"]; 
    } else { 
     $sel = ''; 
     $ch_for = ''; 
    } 
    ?> 

    <div class="checkbox form-inline"> 
     <label><input <?php echo $sel; ?> type="checkbox" name="ch_name[]" value="ch<?php echo $x; ?>">CH<?php echo $x; ?></label> 
     <input type="text" name="ch_for[]" value="<?php echo $ch_for; ?>" placeholder="Channel details" class="form-control ch_for"> 
    </div>          
    <?php 
} 

你在你的其他分支覆蓋$ch_for以來第一個關鍵是ch7,因此第一循環(ch1$ch_name並因此觸發其他)覆蓋$ch_for

+0

啊對不起,我不明白你的意思。你能告訴我,我需要寫什麼? –

+0

您的'$ ch_for ='';'在循環的第一次迭代中覆蓋整個數組。 – ccKep

+0

哦,我修好了。我明白了,謝謝@ccKep :) –

1

你的陣列是聯想array.SO在array_keys使用in_array()。像這個..

<?php 
$array = array('ch7'=>'Seven','ch8'=>'Eight'); 

$keys = array_keys($array); 

//print_r($keys); 

for ($x=1; $x<=12; $x++) { 
    if( in_array('ch'.$x,$keys)) { 
     $sel = 'checked = "checked" '; 
     echo $array["ch{$x}"].PHP_EOL; 
    } else { 
     $sel = ''; 
     $ch_for = ''; 
    } 
}  

?> 

輸出:

Seven 
Eight 
相關問題