dousi1961 2018-03-08 07:01
浏览 29
已采纳

从动态主数组创建子数组...基于类似的密钥对

I have a dynamic array.I have shown one instance of that array here.though It is not fixed how many keys are present

Array
(
    [lowest] => 1200
    [highest] => 139900
    [cat_0] => Womens Clothing
    [cat_1] => Smart Phones
    [cat_2] => Mens Clothing
    [cat_3] => Electronics
    [chil_cat_0] => 18
    [chil_cat_1] => 12
    [chil_cat_2] => 7
    [chil_cat_3] => 11
    [chil_cat_4] => 17
    [keyword] => 
)

For this array, I want to create sub array..like.

Array
(
    [cat_0] => Womens Clothing
    [cat_1] => Smart Phones
    [cat_2] => Mens Clothing
    [cat_3] => Electronics
)

Note: Based on similar keys.I have to break my main array to sub array

However, the main array could have any number of similar rows.

Please help me out.

  • 写回答

1条回答 默认 最新

  • dongzhong1929 2018-03-08 07:11
    关注

    You could use array_filter() to keep only values that match with keys you want :

    $out = array_filter($array, function($key){
        // Keep only keys that begins by 'cat_'
        return substr($key, 0, 4) == 'cat_' ; 
        // or
        return preg_match('~^cat_[\d]+~',$key) ; // Use cat_ + number
    }, ARRAY_FILTER_USE_KEY);
    print_r($out);
    

    Outputs :

    Array
    (
        [cat_0] => Womens Clothing
        [cat_1] => Smart Phones
        [cat_2] => Mens Clothing
        [cat_3] => Electronics
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器