2015-12-16 47 views
-2

我正在PHP中使用一维数组。我想检测重复值的存在,然后统计重复值的数量并输出结果。例如,假设下面的数组:如果发现任何值重复组合数组php

原始数组:

Array 
    { 
     "OrderId": "1", 
     "ProductOrderedId": "1", 
     "CallerId": "1", 
    }, 
    { 
     "OrderId": "2", 
     "ProductOrderedId": "2", 
     "CallerId": "2", 
    }, 
    { 
     "OrderId": "2", 
     "ProductOrderedId": "3", 
     "CallerId": "2", 
    } 
} 

预期结果:

Array 
    { 
      "OrderId": "1", 
      "ProductOrderedId": "1", 
      "CallerId": "1", 
     }, 
     { 
      "OrderId": "2", 
      "ProductOrderedId": "2,3", 
      "CallerId": "2", 
     } 
    } 
+4

那么你有什么试图解决这个问题?或者你期望有人从头开始为你编码? – JakeGould

回答

3

试试这个代码,希望这有助于你。

$newArrayData = array(); 
     $valuesProduct = array(); 
     foreach ($fetchData as $key => $value) { 

      if (count($value) > 1) { 
       foreach ($value as $keys => $vals) { 
        $valuesProduct[] = $vals['ProductOrderedId']; 
       } 
       $implodeVal=implode(',',$valuesProduct); 
       $newArrayData[]= array('OrderId' => $value[0]['OrderId'], 'CallerId' => $value[0]['CallerId'], 
"ProductOrderedId" => $implodeVal); 

      } else { 
       $newArrayData[]=array('OrderId' => $value[0]['OrderId'], 'CallerId' => $value[0]['CallerId'], 
"ProductOrderedId" => $value[0]['ProductOrderedId']); 
      } 
     } 
     print_r($newArrayData); 
+0

谢谢SunUser。有用。 :) –

0

如果你觉得简单,你也可以使用它。

$values = array(
    array(
     "OrderId"=> "1", 
     "ProductOrderedId"=> "1", 
     "CallerId"=> "1", 
    ), 
    array(
     "OrderId"=> "4", 
     "ProductOrderedId"=> "2", 
     "CallerId"=> "2", 
    ), 
    array(
     "OrderId"=> "4", 
     "ProductOrderedId"=> "3", 
     "CallerId"=> "2", 
    ) 
); 

$temp=array(); 
foreach ($values as $value) { 
    if(isset($temp[$value["OrderId"]])){ 
     $temp[$value["OrderId"]]["ProductOrderedId"]=$temp[$value["OrderId"]]["ProductOrderedId"].",".$value["ProductOrderedId"]; 
    }else{ 
     $temp[$value["OrderId"]]=$value;   
    } 
} 

$final_array= array_values($temp);