我有一个吼叫php while
和for
循环。
在while
循环中,它将$ch_for
数据存储在$ch_for
数组中。
使用print_r
此数组显示以下值:
Array ( [ch7] => Seven [ch8] => Eight )
尝试使用以下行在array
循环中访问此for
数据:
echo $ch_for["ch{$x}"];
但它显示错误消息:非法字符串偏移' ch7'在 ......
While and For Loop
$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
}
var_dump(array_keys($ch_for));
array(2) {
[0]=>
string(3) "ch7"
[1]=>
string(3) "ch8"
}
答案 0 :(得分:1)
您的数组是关联数组。在in_array()
中使用array_keys
。就像这样..
<?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
答案 1 :(得分:0)
您在其他分支中覆盖$ch_for
,因为第一个密钥是ch7
,因此第一个循环(ch1
不在$ch_name
中,因此触发else)覆盖$ch_for
。