douhui1957 2016-08-03 10:12
浏览 72
已采纳

在其sub_arrays中拆分多维数组

I have just had this issue. I have a multidimensional array ($varianti) that looks like this:

Array
(
    [pa_taglia] => Array
        (
            [0] => l
            [1] => m
        )

    [pa_colore] => Array
        (
            [0] => blu
            [1] => giallo
            [2] => rosso
        )

)

What I need is to get different arrays for each sub array so I need this result:

Array
(
    [0] => l
    [1] => m
)
Array
(
    [0] => blu
    [1] => giallo
    [2] => rosso
)

The main problem is that I can get as many sub-arrays as needed (this is for my Woocommerce plugin to create product_variations from attributes) so it needs to be flexible.

This is the code I came up with (after 2 hours...):

$keys = array_keys($varianti);//get the main keys

        //split multidimensional array in sub arrays
        foreach ($keys as $key=>$val){          
            $nr_var[$val]= count($varianti[$keys[$key]]);//create array such as array('key1'=> qty1, 'key2'=> qty2);
            $$val = $varianti[$keys[$key]];//create a variable variable from key
        }
        print_r($nr_var);
        foreach ($nr_var as $chiave=>$valore){
            print_r($$chiave);//retrieve values calling variable variable
        }

I hope this may be of help to anyone.

  • 写回答

4条回答 默认 最新

  • dongxian6285 2016-08-03 10:17
    关注

    You can use extract function which will automatically create new variables basing on the key values:

    extract($varianti);
    var_dump($pa_colore);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器