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条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图