PHP如何删除多维数组中的重复值并合并其他数组

时间:2014-01-08 22:45:42

标签: php arrays multidimensional-array duplicates google-webfonts

我花了几个小时来解决这个问题。 我有一个带有字体详细信息的多维数组,我想合并它以向google web字体发送一个请求。 (每个数组描述不同html标签的字体细节)任何人都可以帮助我吗?

输入:

Array
(
[1] => Array
    (
        [family] => Abril Fatface
        [weight] => regular
        [charset] => latin,latin-ext
    )

[2] => Array
    (
        [family] => Akronim
        [weight] => regular
        [charset] => latin
    )

[3] => Array
    (
        [family] => Akronim
        [weight] => regular, bold
        [charset] => latin
    )

[4] => Array
    (
        [family] => Akronim
        [weight] => regular
        [charset] => latin, latin-ext
    )

[5] => Array
    (
        [family] => Acme
        [weight] => regular
        [charset] => latin
    )


)

输出:

Array
 [0]   (
        [family] => Abril Fatface
        [weight] => regular
        [charset] => latin,latin-ext

    )

[1] (
        [family] => Akronim
        [weight] => regular, bold
        [charset] => latin,latin-ext

    )
[2] (
        [family] => Acme
        [weight] => regular
        [charset] => latin

    )

1 个答案:

答案 0 :(得分:0)

<强>功能

function font_merge_unique($col, $arr, $exj)
{
    $test = array();

    foreach($arr AS $key => $row)
    {
        $test[$key] = strtolower(preg_replace('/[^A-Za-z0-9]/', '', $row[$col]));
        foreach($exj AS $index)
        {
            $arr[$key][$index] = array_map('trim', (is_array($arr[$key][$index]) ? $arr[$key][$index] : explode(',', $arr[$key][$index])));
        }
    }

    $unique = array_unique($test);

    $dupes = array_diff_key($test, $unique);

    $list = array();

    foreach($unique AS $key => $n)
    {
        $list[$key] = $arr[$key];
    }

    foreach($dupes AS $di => $row)
    {
        $index = array_search($row, $unique);

        foreach($exj AS $merge)
        {
            $list[$index][$merge] += $arr[$di][$merge];
        }
    }

    foreach($list AS $index => $row)
    {
        foreach($exj AS $merge)
        {
            $list[$index][$merge] = implode(',', $list[$index][$merge]);
        }
    }

    return array_values($list);
}

<强>用法

  • Param 1(String)要使其唯一的值的键名。
  • Param 2(数组)待处理。
  • Param 3(Array)处理数组中的键列表make(String | Array)值是一个唯一的逗号分隔字符串。

    font_merge_unique('family', $array, array('weight','charset'))

<强>结果

Array
(
    [0] => Array
        (
            [family] => Abril Fatface
            [weight] => regular
            [charset] => latin,latin-ext
        )

    [1] => Array
        (
            [family] => Akronim
            [weight] => regular,bold
            [charset] => latin,latin-ext
        )

    [2] => Array
        (
            [family] => Acme
            [weight] => regular
            [charset] => latin
        )

)