duansaoguan7955 2018-12-21 19:25
浏览 92
已采纳

在php中搜索foreach循环中的动态键值

I feel like i'm missing something quite simple. What are some of the best ways to iterate through combinations of $key names -- doing something different for each-- in a php foreach loop?

I have a number of values in an array with key values that follow the same naming format.

Example:

$rec_items['title3'] = implode($meta['title3']);
$rec_items['title4'] = implode($meta['title4']);
$rec_items['title5'] = implode($meta['title5']);

The $rec_items array also contains other values that do not follow this naming convention (or data type).

I'm looping through $rec_items with a foreach loop. I would like to be able to dynamically cycle through key names in $rec_items, and 'do something' when a key is found that matches title*. I've tried pushing numeric numbers from a counter variable into key names to be searched for (like below):

foreach ($rec_items as $key => $value){
    $c = 0;
    if(!empty($key[${'title'.$c}]){
        $c++;
        //do something


}

I believe that I cannot pass the value ${'title'.$c} into $key[] and have tried to pass the value of ${'title'.$c} as a string with no luck.

I just share the above to try to highlight what i'm trying to achieve.

(1) dynamically loop through key names in the format 'title*'

(2) if the key name is present in the $rec_items array ... do something.

  • 写回答

1条回答 默认 最新

  • dongxian7489 2018-12-21 19:56
    关注

    I'm not sure what your original code was trying for; you appeared to be treating the array key like an array itself? Using a variable variable? Anyway, you just need a simple string search of the key. You can use regular expressions or whatever you like for more complex matching.

    <?php
    $rec_items = ["foo"=>12, "bar"=>34, "title1"=>56, "title2"=>78, "baz"=>90];
    foreach ($rec_items as $k=>$v) {
        if (strpos($k, "title") === 0) {
            echo "$k = $v
    ";
        }
    }
    

    Output:

    title1 = 56
    title2 = 78
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 github符合条件20分钟秒到账,github空投 提供github账号可兑换💰感兴趣的可以找我交流一下
  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?