PHP-如何在数组中查找重复的值分组 [英] PHP - How do you find duplicate value groupings in an array

查看:327
本文介绍了PHP-如何在数组中查找重复的值分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串值数组,有时会形成重复的值模式('a','b','c','d')

I have an array of string values which sometimes form repeating value patterns ('a', 'b', 'c', 'd')

$array = array(
    'a', 'b', 'c', 'd',
    'a', 'b', 'c', 'd',
    'c', 'd',
);

我想根据数组顺序找到重复的模式,并按相同的顺序将它们分组(以保持它).

I would like to find duplicate patterns based on the array order and group them by that same order (to maintain it).

$patterns = array(
    array('number' => 2, 'values' => array('a', 'b', 'c', 'd')),
    array('number' => 1, 'values' => array('c'))
    array('number' => 1, 'values' => array('d'))
);

请注意,[a,b],[b,c]和& [c,d]本身不是模式,因为它们位于较大的[a,b,c,d]模式内,最后一个[c,d]集仅出现一次,因此也不是模式-只是各个值' c'和'd'

另一个例子:

$array = array(
    'x', 'x', 'y', 'x', 'b', 'x', 'b', 'a'
  //[.......] [.] [[......]  [......]] [.]
);

产生

$patterns = array(
    array('number' => 2, 'values' => array('x')),
    array('number' => 1, 'values' => array('y')),
    array('number' => 2, 'values' => array('x', 'b')),
    array('number' => 1, 'values' => array('a'))
);

我该怎么做?

推荐答案

字符数组只是字符串.正则表达式是字符串模式匹配之王.添加递归,即使从字符数组来回转换,解决方案也非常优雅:

Character arrays are just strings. Regex is the king of string pattern matching. Add recursion and the solution is pretty elegant, even with the conversion back and forth from character arrays:

function findPattern($str){
    $results = array();
    if(is_array($str)){
        $str = implode($str);
    }
    if(strlen($str) == 0){ //reached the end
        return $results;
    }
    if(preg_match_all('/^(.+)\1+(.*?)$/',$str,$matches)){ //pattern found
        $results[] = array('number' => (strlen($str) - strlen($matches[2][0])) / strlen($matches[1][0]), 'values' => str_split($matches[1][0]));
        return array_merge($results,findPattern($matches[2][0]));
    }
    //no pattern found
    $results[] = array('number' => 1, 'values' => array(substr($str, 0, 1)));
    return array_merge($results,findPattern(substr($str, 1)));
}

您可以在此处进行测试: https://eval.in/507818 https://eval.in/507815

You can test here : https://eval.in/507818 and https://eval.in/507815

这篇关于PHP-如何在数组中查找重复的值分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆