dongquanjie9328 2017-01-22 04:50
浏览 9
已采纳

为什么我无法使用它的密钥访问数组元素?

I have a bellow php while and for loop.

In while loop it's storing $ch_for data in $ch_for array.

Using print_r this array is showing these value :

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

And trying to access this array data in for loop using this line :

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

But it's showing an error message : Illegal string offset 'ch7' in ...

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
}

Result of var_dump(array_keys($ch_for));

array(2) {
  [0]=>
  string(3) "ch7"
  [1]=>
  string(3) "ch8"
}
  • 写回答

2条回答 默认 最新

  • doubinduo3364 2017-01-22 05:03
    关注

    You're overwriting $ch_for in your else-branch since the first key is ch7, hence the first loop (ch1 is not in $ch_name and thus triggers the else) overwrites $ch_for.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog