doutangxi2144 2018-10-02 08:11
浏览 20
已采纳

关联数组循环

I had this i array and i try to loop trough.

Output of:<?php print_r($this);?>

[text] => a:2:{i:0;a:2:{s:5:"value";s:2:"de";s:5:"label";s:70:"<img src="assets/images/e/de-02d3d6ee.jpg"  width="40" height="28" alt="">";}i:1;a:2:{s:5:"value";s:2:"en";s:5:"label";s:70:"<img src="assets/images/7/en-c5c09767.jpg"  width="40" height="28" alt="">";}}

I tried:

<?php $str ='de'; ?>

    <?php foreach ($this->text as $key => $item):?>
        <?php if ($key == $str):?>
            <span class="firstelement hide-on-mobile"><?php echo $item; ?></span>
        <?php endif;?>
    <?php endforeach;?>

I got no output.

  • 写回答

2条回答 默认 最新

  • dsfsd43523 2018-10-02 08:26
    关注

    First of all, your array seems to be serialized. To access it with code, you would need to unserialize() it first. (In case you did not do this already)

    $labels = unserialize($this->text);
    

    The problem you have then is, that you misinterpreted the structure of your array. Your array is built like this:

    $labels = [
        0 => [
            'value' => 'de',
            'label' => '<img ... />'
        ],
        1 => [
            'value' => 'en',
            'label' => '<img ... />'
        ]
    ]
    

    As you can see, it is an array that contains arrays itself. (multidimensional array) When the array gets iterated in your for loop, $key gets assigned the outer keys, so 0 and 1. What you want instead, is to access the inner keys. This can only be done by accessing them directly:

    for($labels as $value) {
        if ($value['value'] === $str) {
            ?>
            <span class="firstelement hide-on-mobile"><?= $value['label'] ?></span>
            <?php
        }
    }
    

    As you can see, the for loop neither accesses the outer keys anymore, because they are not relevant, as well as accessing the inner array's fields with $value['value'] and $value['label'] directly.

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

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计