缺乏知识我会是一个多维PHP,让我很困惑继续我的项目,任何人都可以帮助我多维PHP?所以,我有一些多维PHP,然后我希望从具有特定条件的随机数组中获得两个唯一值。有关详细信息,请访问:
$array = Array(
"LABEL1" => Array(
'value 1',
'value 2',
'value 3'
),
"LABEL2" => Array(
'value 1'
),
"LABEL3" => Array(
'value 1',
'value 2'
),
"LABEL n" => Array(
'value n'
)
)
$output = random($array);
print_r($output);
//output a $output
Array(
[LABEL unique n] => Array(
[0] => 'value 1'
)
[LABEL unique n] => Array(
[1] => 'value 2'
[n] => 'value n'
)
)
//or
Array(
[LABEL1] => Array(
[0] => 'value 1' // always index [0] from LABEL n
)
[LABEL3] => Array(
[1] => 'value 2' //get index > [0] from LABEL n
)
)
//or
Array(
[LABEL2] => Array(
[0] => 'value 1' // always index [0] from LABEL n
)
[LABEL1] => Array(
[1] => 'value 2' //get index > [0] from LABEL n
[2] => 'value 3' //get index > [0] from LABEL n
)
)
//or
Array(
[LABEL2] => Array(
[0] => 'value 1' // always index [0] from LABEL n
)
[LABEL3] => Array(
[1] => 'value 2' //get index > [0] from LABEL n
)
)
不可能吗?
答案 0 :(得分:0)
给出您的示例输入时,此代码中的问题是:
当"第二个随机定位的子阵列"只有一个元素,并且该元素的键与"第一个随机定位的子数组#34;相同,那么第二个子数组在结果数组中将为空。执行演示链接以揭示此问题。
代码:(Demo)
$array=[
"LABEL1"=>['value 1','value 2','value 3'],
"LABEL2"=>['value 1'],
"LABEL3"=>['value 1','value 2'],
"LABEL9"=>['value n']
];
$rand_keys=array_rand($array,2); // generate an array of two random keys from $array
foreach($rand_keys as $i=>$key){
if($i==0){
$subarray=$array[$key];
$column=array_rand($subarray); // column to be excluded from 2nd iteration's subarray
$result[$key][$column]=$subarray[$column]; // store the randomly selected value
}else{
$diff=array_diff_key($array[$key],[$column=>'']); // store all elements that are not from the same column as first subarray
$result[$key]=$diff; // when subarrays are LABEL2 & LABEL9 or LABEL9 & LABEL2, then the second subarray will be empty
}
}
var_export($result);
可能的输出:
array (
'LABEL1' =>
array (
1 => 'value 2',
),
'LABEL3' =>
array (
0 => 'value 1',
),
)
可能的输出:
array (
'LABEL1' =>
array (
0 => 'value 1',
),
'LABEL2' =>
array (
),
)