动态创建新数组,用第一个数组的特殊值填充每个数组,然后获取它们的组合 [英] Dynamically create new Arrays, fill each with specials values from first array and than get combinations of them
问题描述
this question is a little bit similar to my old one here.
但是现在我只有一个动态填充的数组
But now I've got only one dynamically filled array
Array (
[8] => 3-Blue
[9] => 3-Red
[10] => 4-L
[11] => 4-XL
...
...
)
对于值前面的每个数字,我需要一个新数组.因此,对于此示例,我需要这两个
for each number in front of the value, I need a new array. So for this example I need these two
Array (
[8] => Blue
[9] => Red
)
Array (
[10] => L
[11] => XL
)
密钥应保持不变.如果无法做到这一点,则密钥应位于值 L-10
The key should stay the same. If this is not possible, than the keys should be in the value L - 10
而不是我需要组合这些数组,并在像这样的新数组中获得没有重复的可能组合.
than I need to combine those arrays, and get the possible combinations without duplicates in a new array like this.
Array (
[0] => Blue | L - 8,10
[1] => Blue | XL - 8,11
[2] => Red | L - 9,10
[3] => Red | XL - 9,11
)
每个值之后,之前必须有数组形式的键.
after each value, there must be the keys form the arrays before.
这甚至可能吗?如果可以,怎么办?
is this even possible?! and if yes, how?
推荐答案
您可以使用嵌套的 foreach($ arr as $ key => $ val)循环简单地迭代两个数组.
在这里,我使用 sprintf
函数而不是字符串连接,只是因为它使预期的输出格式更加清晰.
You can simply iterate both arrays using nested foreach ($arr as $key => $val)
loop.
Here I use the sprintf
function instead of string concatenation, simply because it makes the intended output format more clear.
$color_array = array(8 => "Blue", 9 => "Red");
$size_array = array(10 => "L", 11 => "XL");
$result = array();
// For each key => value pair in the color array
foreach ($color_array as $color_key => $color) {
// For each key => value pair in the size array
foreach ($size_array as $size_key => $size) {
// Generate the result string with "sprintf", then append it to the result array
$result[] = sprintf("%s | %s - %d,%d", $color, $size, $color_key, $size_key);
}
}
var_dump($result);
// array(4) {
// [0]=> string(15) "Blue | L - 8,10"
// [1]=> string(16) "Blue | XL - 8,11"
// [2]=> string(14) "Red | L - 9,10"
// [3]=> string(15) "Red | XL - 9,11"
// }
您可以使用 array_unique
对结果数组进行重复数据删除.但是,如果两个输入数组都是唯一的,那么您的输出集也应该是唯一的.
You can dedupe the result array using array_unique
. However, if both of your input arrays are unique, your output set should be unique as well.
这篇关于动态创建新数组,用第一个数组的特殊值填充每个数组,然后获取它们的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!