我在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",
}
}
答案 0 :(得分: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);
答案 1 :(得分: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);