在其sub_arrays中拆分多维数组 [英] Split multidimensional array in its sub_arrays
问题描述
我刚遇到这个问题.我有一个看起来像这样的多维数组($ varianti):
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
)
主要问题是我可以根据需要获得任意数量的子数组(这是我的Woocommerce插件从属性创建product_variations的原因),因此它必须具有灵活性.
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.
这是我想出的代码(2小时后...):
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.
推荐答案
您可以使用 extract
函数将根据键值自动创建新变量:
You can use extract
function which will automatically create new variables basing on the key values:
extract($varianti);
var_dump($pa_colore);
这篇关于在其sub_arrays中拆分多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!