Karuppiah RK
Karuppiah RK

Reputation: 3964

find same numbers in between -to- and group them

Here I want to find the same numbers in between - -

For example : Here (6-85-,7-85-,8-113-,) same numbers are 85. I want to find them and group them (add comma) like this

6,7

8

Another example :

2-1-,1-29-,4-57-,5-57-,6-85-,7-85-,8-113-,

2

1

4,5

6,7

8

Is there any way to do this in php? I have searched on here and other forums but never get any idea..

Upvotes: 1

Views: 45

Answers (1)

Dan
Dan

Reputation: 11084

This is how I would do it:

$collect = array();

$s="2-1-,1-29-,4-57-,5-57-,6-85-,7-85-,8-113-,";

$a = explode(',', $s);

foreach($a as $v){
    $m = explode('-',$v);
    if( count($m) >= 2 ){
        $collect[$m[1]][] = $m[0];
    }
}

foreach($collect as $match){
    echo implode(',', $match)."\n";
}

Upvotes: 2

Related Questions