A PHP face test, let's see

Source: Internet
Author: User
$listData = [    '111' => ['a', 'b', 'c', 'a'],    '222' => ['d', 'e', 'f', 'f', 'b'],    '333' => ['g', 'h'],    '444' => ['i', 'j'],    ...];

Define a function to pass in $listdata
If 111 the elements inside, and 222/333/444 ... inside the elements have duplicates, return false
If 222 the elements inside, and 111/333/444 ... inside the elements have duplicates, return false
If 333 the elements inside, and 111/222/444 ... inside the elements have duplicates, return false
If...

Allow 111/222/333/444 to repeat itself inside the element, return True
Other conditions return True

Known:
$listData length Unknown
111/222/333/444 ... The length of the Unknown
111/222/333/444 ... The elements in the string are strings and numbers

I realized it myself, the feeling algorithm is very bad, ask there is no other way

function test ($array) {    $tempValueList  = [];    foreach ($array as $key => $valueList) {                foreach ($valueList as $value) {                        $tempValueList[]    = $key . '~' . $value;        }    }    $result         = true;    foreach ($array as $key => $valueList) {                foreach ($valueList as $value) {                        foreach ($tempValueList as $_value) {                                $pos    = strpos($_value, '~');                $_key   = substr($_value, 0, $pos);                $_val   = substr($_value, $pos + 1);                if ($key == $_key) {                    continue;                }                if ($_val == $value) {                    $result = false;                    break 3;                }            }        }    }    return      $result;}

Reply content:

$listData = [    '111' => ['a', 'b', 'c', 'a'],    '222' => ['d', 'e', 'f', 'f', 'b'],    '333' => ['g', 'h'],    '444' => ['i', 'j'],    ...];

Define a function to pass in $listdata
If 111 the elements inside, and 222/333/444 ... inside the elements have duplicates, return false
If 222 the elements inside, and 111/333/444 ... inside the elements have duplicates, return false
If 333 the elements inside, and 111/222/444 ... inside the elements have duplicates, return false
If...

Allow 111/222/333/444 to repeat itself inside the element, return True
Other conditions return True

Known:
$listData length Unknown
111/222/333/444 ... The length of the Unknown
111/222/333/444 ... The elements in the string are strings and numbers

I realized it myself, the feeling algorithm is very bad, ask there is no other way

function test ($array) {    $tempValueList  = [];    foreach ($array as $key => $valueList) {                foreach ($valueList as $value) {                        $tempValueList[]    = $key . '~' . $value;        }    }    $result         = true;    foreach ($array as $key => $valueList) {                foreach ($valueList as $value) {                        foreach ($tempValueList as $_value) {                                $pos    = strpos($_value, '~');                $_key   = substr($_value, 0, $pos);                $_val   = substr($_value, $pos + 1);                if ($key == $_key) {                    continue;                }                if ($_val == $value) {                    $result = false;                    break 3;                }            }        }    }    return      $result;}

Look, the two previous answers are useless. LZ really poor.

My sub-array is defined as a single array such as [' A ', ' B ', ' C ', ' a '].

My answer:

$result = array();foreach ($listData as $line) {    //子数组内部去重,再组装回原来的格式    $result[] = array_unique($line);}//子数组先去重再合并的结果数量 和 先合并子数组再去重的结果数量 做比较。//如果是相同的,意味着不存在跨子数组的重复,只存在子数组内部重复,所以`True`var_dump(count(array_merge(...$result)) === count(array_unique(array_merge(...$listData))));

I have this answer call system functions more times, it seems concise, but PHP array_xxx such functions a large part of the performance is not an advantage, if not these functions, can be relatively increased operational efficiency.

At present, the efficiency of @springhack is the highest. and can maintain maximum efficiency in all situations.

Accessible reference information for easy comprehension:

Raw data:

$listData = [    '111' => ['a', 'b', 'c', 'a'],    '222' => ['d', 'e', 'f', 'f', 'b'],    '333' => ['g', 'h'],    '444' => ['i', 'j']];

And then $result the end is this:

$listData = [        '111' => ['a', 'b', 'c'],        '222' => ['d', 'e', 'f', 'b'],        '333' => ['g', 'h'],        '444' => ['i', 'j']];

Sub-array first to re-merge results

Array(    [0] => a    [1] => b    [2] => c    [3] => d    [4] => e    [5] => f    [6] => b    [7] => g    [8] => h    [9] => i    [10] => j)

For comparison with the number above (the number of elements in the array), the so-called "merge the Subarray first and then redo the result":

Array(    [0] => a    [1] => b    [2] => c    [4] => d    [5] => e    [6] => f    [9] => g    [10] => h    [11] => i    [12] => j)

Loop once, the current element and all other elements of the intersection, the code is as follows:

    function isExistsInOther($data)    {        $temp = [];        $isExists = true;        foreach ($data as $key=>$value) {            $temp = $data;            unset($temp[$key]);            if(!$isExists) break;            @array_walk($temp,function($v,$k) use($value,&$isExists){                if($isExists) {                    $intersect = array_intersect($v,$value);                    if(!empty($intersect)) {                        $isExists = false;                    }                }            });        }        return $isExists;    }        $listData = [        '111' => ['a', 'k', 'c', 'a'],        '222' => ['d', 'e', 'f', 'f', 'b'],        '333' => ['g', 'e'],        '444' => ['i', 'j']    ];    $result = isExistsInOther($listData);    var_dump($result);    //true  无交集    //false 有交集

/** * [checkRepeat 检查每个key的数组值是否与其它的有重复值] * @param  [type] $listData [检查的数组] * @return [type]           [array] */function checkRepeat($listData) {    foreach($listData as $key =>$val) {        $check_arr = $listData;        // 删除当前key        unset($check_arr[$key]);        // 合并删除后的数组        $check_arr = array_merge(...$check_arr);        // 判断是否存在交集        $rs[$key] = count(array_intersect($val, $check_arr)) > 0 ? false : true ;    }    return $rs;}$listData = [    '111' => ['a', 'b', 'c', 'a'],    '222' => ['d', 'e', 'f', 'f', 'b'],    '333' => ['g', 'h'],    '444' => ['i', 'j'],];$rs = checkRepeat($listData);

function check($arr){  $chk = [];  foreach ($arr as $k => $v)    foreach ($v as $i)    {      if (isset($chk[$i] && $chk[$i] != $k)        return false;      $chk[$i] = $k;    }  return true;}

Claw machine code Word, should be the most efficient, self-commissioning under.

Since all the answers are given above, let me add that multidimensional arrays

/** * 多维数组去重 * @param array  * @return array */function super_unique($array){    $result = array_map("unserialize", array_unique(array_map("serialize", $array)));    foreach ($result as $key => $value)    {        if ( is_array($value) ) {            $result[$key] = super_unique($value);        }    }    return $result;}

Multidimensional array de-weight

$listData = array_values($listData);foreach ($listData as $k => $v) {    foreach ($listData as $n => $m) {        if($k == $n) continue;        if(array_intersect($v , $m)){            
'; } else{
'; } }}

My Answer (principle: loop intersection):


  
    ['a', 'b', 'c', 'a'],    '222' => ['d', 'e', 'f', 'f','b'],    '333' => ['g', 'h','c'],    '444' => ['i', 'j']];function jiaoji($array){    $listData = array_values($array);    $list = [];    for ($i = 0; $i < count($listData); $i++) {        for ($j = $i+1; $j < count($listData); $j++) {            $list[] = array_intersect($listData[$i],$listData[$j]);        }    }    $result = array_filter($list);    return count($result)==0;}var_dump(jiaoji($list));//bool(false)?>

Can you understand that as long as the values inside this array intersect with each other, then return false ...
The Array_intersect () function seems to work. But the problem is that the value inside an array becomes a decimal group.


  
    ['a', 'b', 'c', 'a'],    '222' => ['d', 'e', 'f', 'f', 'b'],    '333' => ['g', 'h'],    '444' => ['i', 'j'],    ...];function getArr($listData){    $isUnsetFirstKey = false;    $len = count($listData);    if($len<=1) return false;    $firstKey = key($listData);    $firstArr = array_unique($listData[$firstKey]);    $newList = $listData;    unset($newList[$firstKey]);    foreach ($newList as $key => $val) {        $arr = array_unique($val);        $newarr = array_merge($firstArr,$arr);        if(count($newarr) != count(array_unique($newarr))){            $isUnsetFirstKey = true;            unset($newList[$key]);            echo $key . "
"; } } if($isUnsetFirstKey) echo $firstKey . "
"; getArr($newList);}getArr($listData);?>

My answer, check it out, it's awesome.

A one-dimensional array is similar to a two-dimensional array, in-house judgment, the following is a two-dimensional array method, a one-dimensional array is skipped
Compares array lengths before and after an array merge (followed by a unique)

function check_repeat($arr){    $after_arr = [];    // 对比自身    foreach($arr as $index => $value){        $arr[$index] = $after_arr = array_unique($value);        if(count($value) !== count($after_arr)){            return true;        }    }    // 对比其他    $temp = array_shift($arr);    $cnt  = count($temp);    foreach ($arr as $index => $value) {        $cnt += count($value);        $temp = array_merge($temp, $value);    }    return $cnt !== count(array_unique($temp)) ? true : false;}$listData = [    '111' => ['a', 'b', 'c',],    '222' => ['d', 'e', 'f',],    '333' => ['g', 'h'],    '444' => ['i', 'j'],];var_dump(check_repeat($listData));

function test($listData) {    $result = array_map('array_unique', $listData);    foreach ($result as $key => $value) {        $keys = array_values(array_diff(array_keys($result),[$key]));        for($i = 0; $i <= count($keys); $i ++) {            $data = array_merge_recursive($data,$result[$keys[$i]]);            if ($i == (count($keys) -1) ) {                $res = array_intersect($value, $data);            }        }        $data = [];    }    return !empty($res) === true ? false : true;}


  
    ['a', 'b', 'c', 'a'],    '222' => ['d', 'e', 'f', 'f', 'b'],    '333' => ['g', 'h'],    '444' => ['i', 'j'],];$temp = array();foreach ($listData as $key => $xxx) {    foreach ($xxx as $value) {        if (in_array($value, $temp)) {            echo $value.' from '.$key.' is in array';            exit();        }    }    $temp = array_merge($temp, $xxx);}echo 'You should get a True!';

Not a few lines, to meet the demand.

Before restoring the
Shiji's answer

Array_pop first, take out the last item. And then fetch the set of the items array. Returns True if the set has an intersection with the last item (table Duplicates). Loop execution.

Based on the @ Big Woo algorithm improved a bit.

function checkRepeat2($listData){    $check_arr = $listData;    foreach ($listData as $key => $val) {        //之前比较过的key无需再比较        unset($check_arr[$key]);        if ($check_arr) {            // 合并删除后的数组,判断是否存在交集            //As PHP 5.6 you can use array_merge + "splat" operator to reduce a bidimensonal array to a simple array:            if (array_intersect($val, array_merge(...$check_arr))) {                return false;            }        }    }    return true;}

Don't know if this is the case:

$new_arr = [];foreach ($listData as $key => $value) {    foreach ($value as $k => $v) {        $kv = $k . $v;        if (in_array($kv, $new_arr)) {            echo '有重复';exit;        } else {            $new_arr[] = $kv;        }    }}
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.