How to find multiple substrings in a string in php

I have these tables. In the first table, I have the transaction ID and the products purchased in that transaction.

  TID         Products
   1           1,2,5 
   2            2,4 
   3            2,3 
   4           1,2,4 
   5            1,3 
   6            2,3 
   7            1,3 
   8          1,2,3,5 
   9           1,2,3 

      

What I want to do with this data is counting the number of times the stencil appears in the Products column. For example, itemset {1,2} is found 4 times in the Products column, there is no problem, but 1,3 is only found 2 times, but as you can see in the Products column it appears 4 times.

ItemSet     Sup. count 
  1,2            4 
  1,3            2 
  1,4            0 
  1,5            0 
  2,3            4 
  2,4            2 
  2,5            1 
  3,4            0 
  3,5            1 
  4,5            0 

      

This is the php code I used to find matches in Sup. counter. if i find all matches in the item set when i get two digits like 12 or more it says it found 1 and 2 again so i put a border. So I am stuck at this place.

$result_support =  array_fill ( 0 , $count_itemsets , 0 );
$count_result_array = count($result_array);

for($i = 0; $i < $count_itemsets; $i++){
    for($j = 0; $j < $count_result_array; $j++){
        $string = $result_array[$j];
        if (preg_match('~\\b' . $result_itemset[$i] . '\\b~i', $string, $m)) {
            $result_support[$i] = $result_support[$i] + 1;

        }
    }
}

      

+3


source to share


1 answer


$array1 = array(
   1=>           '1,2,5',
   2 =>           '2,4', 
   3=>           '2,3', 
   4 =>           '1,2,4', 
   5 =>           '1,3', 
   6=>           '2,3',
   7 =>           '1,3',
   8  =>           '1,2,3,5',
   9 =>           '1,2,3');

$produCt =array();
foreach ($array1 as $index =>$val){ 
   $arra = explode(',', $val);
    if(count($arra)>2){
         for($i=0;$i<count($arra);$i++){
             for($j=$i+1;$j<count($arra);$j++){
                 $produCt[] = $arra[$i].",".$arra[$j];              
             }              
           }
    }else{
      $produCt[] =$val;
    }
}
$prdtCount =array_count_values($produCt);
var_dump($prdtCount);

      

I assume your required output is



array (size=8)
  '1,2' => int 4
  '1,5' => int 2
  '2,5' => int 2
  '2,4' => int 2
  '2,3' => int 4
  '1,4' => int 1
  '1,3' => int 4
  '3,5' => int 1

      

0


source







All Articles