如何在php中的字符串中找到多个子字符串

时间:2014-12-11 09:20:10

标签: php

我有这些表格。在第一个表格中,我有交易ID和在该交易中购买的产品。

  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 

我想对此数据执行的操作是计算“产品”列中项目集的出现次数。例如,在“产品”列中找到项目集{1,2} 4次,没有问题,但1,3次只发现2次,但正如在“产品”列中看到的那样,它出现了4次。

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 

这是我用来在Sup中找到匹配项的php代码。计数列。如果我找到项目集中的所有巧合,当我得到12位或更多的两位数字时,它会说它再次找到1和2,这就是我放置边界的原因。所以我被困在这个地方。

$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;

        }
    }
}

1 个答案:

答案 0 :(得分:0)

$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);

我假设您所需的输出是

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
相关问题