PHP如何基于现有多维数组生成带指定键名的全组合新数组
PHP 多数组笛卡尔积生成带自定义键名的新数组
以下是直接可运行的实现代码:
<?php // 原数组定义 $main_array = [ ["XS", "S", "M", "L", "XL"], ["12", "34", "56"], ["Series 6/SE-44 MM", "Series 7-45 MM"] ]; $result = []; // 三层遍历生成全量笛卡尔积 foreach ($main_array[0] as $raw_size) { $pa_clothes = strtolower($raw_size); foreach ($main_array[1] as $raw_num) { $test = $raw_num; foreach ($main_array[2] as $raw_watch) { // 正则提取手表尺寸,转换为指定格式 preg_match('/(\d+)\s*MM$/i', $raw_watch, $match_res); $pa_apple_watch = strtolower($match_res[1] . '-mm'); $result[] = [ 'pa_clothes' => $pa_clothes, 'pa_apple_watch' => $pa_apple_watch, 'test' => $test ]; } } } // 输出结果验证 print_r($result); ?>
逻辑说明
- 三层循环遍历三个子数组的所有取值,自动生成532=30条全组合数据,和你给出的预期结果完全匹配
- 字段转换规则严格符合要求:
pa_clothes:原第一个子数组的尺码直接转小写test:原第二个子数组的数值直接取值pa_apple_watch:从原第三个子数组的字符串中提取末尾的数字,拼接为x-mm小写格式
如果需要支持任意维度数组的通用笛卡尔积生成,不需要手动写多层循环,可以使用递归版本实现:
<?php // 通用笛卡尔积生成函数 function generate_cartesian($arrays) { $result = [[]]; foreach ($arrays as $index => $value_list) { $temp = []; foreach ($result as $product) { foreach ($value_list as $val) { $temp[] = $product + [$index => $val]; } } $result = $temp; } return $result; } // 调用函数后处理字段格式 $all_combination = generate_cartesian($main_array); $result = []; foreach ($all_combination as $item) { preg_match('/(\d+)\s*MM$/i', $item[2], $match_res); $result[] = [ 'pa_clothes' => strtolower($item[0]), 'test' => $item[1], 'pa_apple_watch' => strtolower($match_res[1] . '-mm') ]; } ?>
内容的提问来源于stack exchange,提问作者user3012959
相关产品推荐
相关产品推荐

