dongzhun4898
2016-05-17 15:11
浏览 102
已采纳

删除数组中具有逗号分隔值的重复项

I have an array of languages that looks like this: (this data is pulled from mysql stored as: e.g. field value: greek, polish)

 Array
(
[0] => 
[1] => french
[2] => french, greek
[3] => german
[4] => greek
[5] => greek, polish
[6] => italian
[7] => spanish
[8] => spanish, italian
[9] => spanish, portuguese
)

I have tried using array_unique($languages) but the output stays the same.

I assume it is because of the comma.

Any idea on how to just have unique values? e.g. one each of: french, greek, german, polish, italian, spanish, and portuguese?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongsi1944 2016-05-17 15:18
    已采纳

    Make a plain array from input

    $res = array();
    foreach ($array  as $item)
      $res = array_merge($res, explode(', ', $item)); 
    

    and then use array_unique($res)

    点赞 评论
  • dongxifu5009 2016-05-17 15:17
    $data = array_map(function ($item) {
        // explode values by "," and trim spaces
        return array_map('trim', explode(',', $item));
    }, $your_data);
    
    // merge all nested arrays from $data and return unique
    return array_unique(
        call_user_func_array('array_merge', $data);
    );
    

    Your result will be:

    Array
    (
    [0] => 
    [1] => french
    [2] => greek
    [3] => german
    [4] => polish
    [5] => italian
    [6] => spanish
    [7] => portuguese
    )
    
    点赞 评论
  • dpygo62420 2016-05-17 15:28

    Possible solution:

    function getUniqueSubValues($array) {
        $result = [];
        foreach($array as $element) {
            $result += preg_split('/\s*,\s*/', $element);
        }
        return array_unique($result);
    }
    

    I'm looping over all values inside the array and splitting each of them further into subvalues.

    I'm using preg_split('/\s*,\s*/', ...) instead of explode(',', ...) because otherwise the space after the , would be kept and we would have to trim it.

    I'm merging all subvalues into the results array, and at the end I'm returning the unique values of that array.

    点赞 评论

相关推荐 更多相似问题