转换此PHP数组的最简单方法是什么?
$a = array('A' => array(1, 2),
'B' => array(3, 4),
'C' => array(5));
进入这个:
$result = array(
array('A' => 1, 'B' => 3, 'C' => 5),
array('A' => 1, 'B' => 4, 'C' => 5),
array('A' => 2, 'B' => 3, 'C' => 5),
array('A' => 2, 'B' => 4, 'C' => 5),
);
$a可能有很多不同的密钥,我在开发期间不知道.所以我需要
生成给定数组中的所有组合.
更新:
我必须生成基于传入数组的URL.所以我不知道在开发期间会得到多少参数.我只有参数数组,它可以是例如
$a = array('A' => array(5,3, 1));
结果将是:
$result = array(
array('A' => 5),
array('A' => 3),
array('A' => 1));
要么
$a = array('X' => array(5), 'D' => array(4, 7));
结果将是:
$result = array(
array('X' => 5, 'D' => 4),
array('X' => 5, 'D' => 7));
解决方法:
像这个:
$a = array('A' => array(1, 2),
'B' => array(3, 4),
'C' => array(5));
function get_combinations($arrays) {
$result = array(array());
foreach ($arrays as $property => $property_values) {
$tmp = array();
foreach ($result as $result_item) {
foreach ($property_values as $property_value) {
$tmp[] = array_merge($result_item, array($property => $property_value));
}
}
$result = $tmp;
}
return $result;
}
产量
var_dump(get_combinations($a));
array (size=4)
0 =>
array (size=3)
'A' => int 1
'B' => int 3
'C' => int 5
1 =>
array (size=3)
'A' => int 1
'B' => int 4
'C' => int 5
2 =>
array (size=3)
'A' => int 2
'B' => int 3
'C' => int 5
3 =>
array (size=3)
'A' => int 2
'B' => int 4
'C' => int 5