我正在寻找将元素组合到分类数组中。与$ Finish相比,了解$ Start的组织方式。
您能解释一下,或许可以展示如何有效地进行转换吗?
谢谢!
$Start = array(
array ('Doctor1', 'visitDateA'),
array ('Doctor2', 'visitDateB'),
array ('Doctor3', 'visitDateC'),
array ('Doctor1', 'visitDateD'),
array ('Doctor1', 'visitDateE'),
array ('Doctor2', 'visitDateF'),
array ('Doctor4', 'visitDateG')
);
$Finish = array(
array (
'Doctor1',
array('visitDateA', 'visitDateD', 'visitDateE')),
array (
'Doctor2',
array('visitDateB', 'visitDateF')),
array (
'Doctor3',
array('visitDateC')),
array (
'Doctor4',
array('visitDateG'))
);
答案 0 :(得分:1)
这将以您需要的方式产生结果:
$Start = array(
array ('Doctor1', 'visitDateA'),
array ('Doctor2', 'visitDateB'),
array ('Doctor3', 'visitDateC'),
array ('Doctor1', 'visitDateD'),
array ('Doctor1', 'visitDateE'),
array ('Doctor2', 'visitDateF'),
array ('Doctor4', 'visitDateG')
);
$Doctors = $Finish = array();
foreach( $Start as $item ) {
if ( !isset( $Doctors[$item[0]] ) ) {
$Doctors[$item[0]] = array( $item[0], array() );
$Finish[] = &$Doctors[$item[0]];
}
if ( !in_array( $item[1], $Doctors[$item[0]][1] ) )
$Doctors[$item[0]][1][] = $item[1];
}
答案 1 :(得分:0)
这可能不是你想要的答案,但我建议这样做。因为访问代码中的值很容易。
<?php
$Start = array(
array ('Doctor1', 'visitDateA'),
array ('Doctor2', 'visitDateB'),
array ('Doctor3', 'visitDateC'),
array ('Doctor1', 'visitDateD'),
array ('Doctor1', 'visitDateE'),
array ('Doctor2', 'visitDateF'),
array ('Doctor4', 'visitDateG')
);
foreach($Start as $k => $v){
if(in_array($v[0], $v)){
$Finish[$v[0]][] = $v[1];
}
}
ksort($Finish); // Doctor1 will always be first.
print_r($Finish);
?>
输出:
Array
(
[Doctor1] => Array
(
[0] => visitDateA
[1] => visitDateD
[2] => visitDateE
)
[Doctor2] => Array
(
[0] => visitDateB
[1] => visitDateF
)
[Doctor3] => Array
(
[0] => visitDateC
)
[Doctor4] => Array
(
[0] => visitDateG
)
)
要访问,您可以写下这样的内容:
if(in_array('visitDateA', $Finish['Doctor1'])){
echo 'Yes' . PHP_EOL;
}
else{
echo 'No' . PHP_EOL;
}
输出:
Yes