【发布时间】:2013-12-04 20:38:30
【问题描述】:
我有一个格式如下的数组:
[8106] => Array (
[id1] => 210470
[id2] => 216298
)
[8107] => Array (
[id1] => 210470
[id2] => 187145
)
[8108] => Array (
[id1] => 187145
[id2] => 216298
)
[8109] => Array (
[id1] => 187145
[id2] => 210470
)
[8110] => Array (
[id1] => 266533
[id2] => 249612
)
[8111] => Array (
[id1] => 249612
[id2] => 266533
)
我需要把它变成以下格式:
[0] => Array (
[0] => 266533
[1] => 249612
)
[1] => Array (
[0] => 187145
[1] => 210470
[2] => 216298
)
基本上,我需要提取所有 id,保留关系,但将它们组合在一起。我有一个功能可以做到这一点,但它需要很长时间(我必须运行的行数长达 30 多分钟)。键和顺序并不重要。关系才是最重要的。我正在寻找一种更快的方法。我正在使用的功能如下:
function getMatchingIDs($filteredArray)
{
$result = array();
$resultCount = 0;
foreach ($filteredArray as $details) {
$imaId1 = inMultiArray($details['id1'], $result);
$imaId2 = inMultiArray($details['id2'], $result);
if ($imaId1 === false && $imaId2 === false) {
$result[$resultCount++] = array(
$details['id1'],
$details['id2'],
);
} elseif (is_numeric($imaId1) === true && $imaId2 === false) {
$result[$imaId1][] = $details['id2'];
} elseif ($imaId1 === false && is_numeric($imaId2) === true) {
$result[$imaId2][] = $details['id1'];
} elseif ($imaId2 != $imaId1) {
$result[$imaId1] = array_merge($result[$imaId1], $result[$imaId2]);
unset($result[$imaId2]);
}
}
return $result;
}
function inMultiArray($elem, $array)
{
if (is_array($array) === true) {
// if the variable $elem is in the variable $array return true
if (is_array($array) === true && in_array($elem, $array) === true) {
return true;
}
// if $elem isn't in $array, then check foreach element
foreach ($array as $key => $arrayElement) {
// if $arrayElement is an array call the inMultiArray function to this element
// if inMultiArray returns true, than return is in array, else check next element
if (is_array($arrayElement) === true) {
$value = inMultiArray($elem, $arrayElement);
if ($value === true) {
return $key;
}
}
}
}
// if isn't in array return false
return false;
}
$filtered = getMatchingIDs($unfiltered);
编辑: 原始数组描述了 id 对之间的关系(未在数组中显示)。期望的输出是关系被进一步定义。如果查看原始数组,元素 8106-8109 只是三个 id 的配对组合。我需要将这三个组合在一起。元素 8110 和 8111 是不同的一对,只是顺序不同。
【问题讨论】:
-
你能用文字描述所需的输出吗?
-
我将请求的信息添加到问题中。谢谢。
-
@kingzero 即使在您的描述之后,我仍然不清楚对这些值进行分组的逻辑是什么。例如,你怎么知道元素 8106-8109 是相互关联的,为什么这些元素中的 id 映射到结果数组中 1 的索引位置?您还提到数字或“行”这是否意味着这些数据来自数据库?如果是这样,您是否尝试过修改您的数据库查询以获得您想要的数据结构?
-
ID 代表数据库中的相似名称。第一个数组是在 MySQL 的 soundex 上从数据库中提取数据,然后通过 PHP 的 levenshtein 函数运行它的结果。 levenshtein() 函数确定产生第一个数组的一对的相关程度。