查找具有相似名称的数组键并重命名

时间:2014-10-21 09:16:01

标签: php arrays foreach array-merge array-difference

我正在寻找一个能找到名称相似的数组键并重命名的函数。

示例:

Array('Joes house' => 'some text', 'Joe`s House' => 'more Text', 'Bob' => 'text...')

结果:

Array('New Key' => 'some text', 'New Key' => 'more Text', 'Bob' => 'text...')

我想到了这些功能的混合:

array_keys($array)
similar_text($word1' $word2)

在foreach Loop。

有什么想法吗? 非常感谢!

编辑:

在第一篇文章中,我忘了我的数组里面有一个子数组...... 我现在已经建立了我的功能。这是一个很好的方式来完成这项工作还是有更有效的方式?

$array = array('Joe\'s House' => array('ABB', 'CDE'), 'Joes Pizza' => 'GDU', 'Jims House' => 'RDS', 'Joe Horse' => 'ABB', 'Joes Housee' => 'HCT');

echo "<pre>Original ";
print_r($array);
echo "</pre>";

$keys = array_keys($array);
$first = null;
$filter = array();
$add = array();

foreach($keys as $key) {
    foreach($keys as $check) {
        similar_text($key, $check, $percent);
        if($percent > 90 && $key != $check) {
            //Buffer first similar array key
            if(empty($first)) {
                $first = $key;
            }
            // build filter array
            $filter[$check] = $array[$check];
            // build add array
            if(is_array($array[$check])) {
                $add[$first] = array_merge($add[$first], $array[$check]);
            }
            else {
                $add[$first][] = $array[$check];
            }
        }
    }
}

$array = array_diff($array, $filter);
$result = array_merge($array, $add);

echo "<pre>To delete ";
print_r($filter);
echo "<pre>To add ";
print_r($add);
echo "Final filtered ";
print_r($result);
echo "</pre>";

输出如下:

Original Array
(
    [Joe's House] => Array
        (
            [0] => ABB
            [1] => CDE
        )

    [Joes Pizza] => GDU
    [Jims House] => RDS
    [Joe Horse] => ABB
    [Joes Housee] => HCT
)

To delete Array
(
    [Joes Housee] => HCT
    [Joe's House] => Array
        (
            [0] => ABB
            [1] => CDE
        )

)

To add Array
(
    [Joe's House] => Array
        (
            [0] => HCT
            [1] => ABB
            [2] => CDE
        )

)

Final filtered Array
(
    [Joes Pizza] => GDU
    [Jims House] => RDS
    [Joe Horse] => ABB
    [Joe's House] => Array
        (
            [0] => HCT
            [1] => ABB
            [2] => CDE
        )

)

1 个答案:

答案 0 :(得分:0)

可能是这样的:

$array = array('Joes house' => 'some text', 'Joe`s House' => 'more Text');
$keys = array_keys($array);
foreach($keys as $key) {
    $key_size = strlen($key);
    foreach($keys as $check) {
        if(((similar_text($key, $check) / $key_size) * 100) > 80 && $key != $check) {
            echo '80% MATCH!';
            //Create new array item
            $array['new_key'] = $array[$check];
            //Delete old array item
            unset($array[$check]);
        }
    }
}