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 无源定位系统的时差估计误差标准差
  • ¥15 请问这个代码哪里有问题啊
  • ¥20 python--version在命令端输入结果Python is not defined怎么办?还有pip不是exe格式是不是没安装成功?
  • ¥15 通过GaussianView进行结构微调消除虚频
  • ¥15 调用transformers库
  • ¥15 由于导出的数据名字中带有/,导致Matlab打不开,怎么办?
  • ¥15 新硬盘安装的程序总是崩溃,提示遇到错误
  • ¥15 openpcdet自制数据集评估bev精度和3d精度相同
  • ¥15 excel 上下按钮 显示行
  • ¥20 云卓h12pro 数传问题