我有一个像 -
这样的多维数组array(
"C" => array('A','A1','A2','B',B1'),
"C1" => array('A','A1','A2','B',B1'),
"A" => array('B','B1','C',C1'),
"B1" => array('A','A1','A2','C',C1'),
"B1" => array('A','A1','A2','C',C1'),
"A2" => array('B','B1','C',C1'),
"A1" => array('B','B1','C',C1')
);
我想要一个脚本,它会为每个键分配给定数组的值,
结果将像 -
C A/A1/A2/B/B1 - A //I can assign any value from A/A1/A2/B/B1
C1 A/A1/A2/B/B1 - A1 //Once A is assigned for the above key then C1 will get value from A1/A2/B/B1 skipping the 'A' which is assigned to key 'C'
A B/B1/C/C1 - B //Now A will get value from B/B1/C/C1
B1 A/A1/A2/C/C1 - A2 //B1 will get value from A2/C/C1
B A/A1/A2/C/C1 - C //Likewise all the values will be assigned uniquely
A2 B/B1/C/C1 - B1
A1 B/B1/C/C1 - C1
条件是不会将相同的值分配给多个键,即所有键都具有不同的值。 (检查以上结果以了解究竟需要分配的内容)
答案 0 :(得分:0)
$data = array(
"C" => array('A','A1','A2','B','B1'),
"C1" => array('A','A1','A2','B','B1'),
"A" => array('B','B1','C','C1'),
"B1" => array('A','A1','A2','C','C1'),
"B" => array('A','A1','A2','C','C1'),
"A2" => array('B','B1','C','C1'),
"A1" => array('B','B1','C','C1')
);
$assigned = array();
$result = array();
foreach($data as $k => $v) {
for($i=0;$i<count($v);$i++) {
if (!in_array($v[$i],$assigned)) {
$assigned[] = $v[$i];
$result[$k] = $v[$i];
break;
}
}
}
var_dump($result);
输出:
array(7) {
["C"]=>
string(1) "A"
["C1"]=>
string(2) "A1"
["A"]=>
string(1) "B"
["B1"]=>
string(2) "A2"
["B"]=>
string(1) "C"
["A2"]=>
string(2) "B1"
["A1"]=>
string(2) "C1"
}
这个解决方案并不好;)如果你将C1定义为数组('A'),那么C1将没有值,以防止你可以尝试检查是否有可能在不同的配置中分配值。
$data = array(
"C" => array('A','A1'),
"C1" => array('A'),
"A" => array('B','B1','C','C1'),
"B1" => array('A','A1','A2','C','C1'),
"B" => array('A','A1','A2','C','C1'),
"A2" => array('B'),
"A1" => array('B','B1','C','C1')
);
$assigned = array();
$keys = array_keys($data);
for($i=0;$i<count($keys);$i++) {
getValue($data, $assigned, $keys, $i);
}
function getValue($data, &$assigned, $keys, &$i, $x = null) {
$j = $x === null ? 0 : array_search($x, $data[$keys[$i]]) +1;
for($j; $j<count($data[$keys[$i]]); $j++) {
$v = $data[$keys[$i]][$j];
if(!in_array($v, $assigned)) {
$assigned[$keys[$i]] = $v;
return;
}
}
$i--;
if ($i < 0) {
throw new Exception('no solutions');
}
$val = $assigned[$keys[$i]];
$assigned[$keys[$i]] = null;
getValue($data, $assigned, $keys, $i, $val);
}
var_dump($assigned);