我有以下多维数组:
$ancestors = array(
[1] =>array("Andrew","Adele"),
[2] =>array("Bertha","Bill","Billy","Blake"),
[3] =>array("Cathy","Case","Cory","Creek","Andrew","Ceaser","Cece","Childer"));
我正在尝试搜索行并返回重复值以及重复出现的最小数字的数组键,并将值返回到关联数组:
$common = array("Andrew"=>"1");
答案 0 :(得分:0)
// merge all array in one
$new = array();
foreach($ancestors as $i)
$new = array_merge($new, $i);
// make array value => count and sort in in descendant order
$ar = array_count_values($new);
arsort($ar);
// save result array while count > 1
$result = array();
foreach($ar as $k => $v) {
if ($v < 2) break;
$result[$k] = array_search($k, $new) + 1;
}
print_r($result);
答案 1 :(得分:0)
首先将所有名称组合成一个数组,名称为键,生成索引数组为值:
foreach ($ancestors as $generation_key => $generation) {
foreach ($generation as $name) {
$combined[$name][] = $generation_key;
}
}
然后将组合结果限制为具有多个名称实例的值:
$duplicates = array_filter($combined, function($x) { return count($x) > 1; });
然后使用min
将数组转换为单个值:
foreach ($duplicates as &$value) {
$value = min($value);
}
unset($value);
答案 2 :(得分:0)
我们必须将每一行与后续行进行比较,因此第1行包含2和3,第2行包含3,第3行没有任何内容(已经比较过)。
为此,我们使用base-1 for
遍历除last之外的所有$ancestors
元素,然后我们将每个名称与更大的祖先进行比较:
$result = array();
/* Loop count($ancestors) -1: */
for( $i = 1; $i<count( $ancestors ); $i++ )
{
/* Loop for each name: */
foreach( current( $ancestors ) as $val )
{
/* If name is already in result, skip: */
if( isset( $result[$val] ) ) continue;
/* Loop for each following ancestors: */
foreach( array_slice( $ancestors, $i, Null, True ) as $key => $row )
{
if( in_array( $val, $row ) ) $result[ $val ] = key( $ancestors );
}
}
next( $ancestors );
}
对于此$ancestors
:
$ancestors = array(
1 =>array( "Andrew","Adele" ),
2 =>array( "Bertha","Bill","Billy","Blake","Adele" ),
3 =>array( "Cathy","Case","Cory","Creek","Andrew","Ceaser","Bill","Cece","Childer" ),
4 =>array( "Cathy" )
);
结果是:
Array
(
[Andrew] => 1
[Adele] => 1
[Bill] => 2
[Cathy] => 3
)