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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀