2012-11-08 116 views
0

我想尝试合并和排序多维数组。目前,该阵列是这样的:合并和订购PHP多维数组

Array 
(
[0] => Array 
    (
     [customerID] => 1234 
     [service] => Car 
     [CSA]  => Jack 
     [status]  => 3 
    ) 

[1] => Array 
    (
     [customerID] => 1234 
     [service] => Cap 
     [CSA]  => Jill 
     [status]  => 3 
    ) 

[2] => Array 
    (
     [customerID] => 1234456 
     [service] => Plate 
     [CSA]  => Jack 
     [status]  => 1 
    ) 

在这个多维数组,在客户将是独一无二的,然而,许多二级阵列采用相同的customerID。同样,在这些阵列中,CSA可能与状态一样。

我想结束数组如下所示:

Array 
(
[0] => Array 
    (
     [customerID] => 1234 
     [service] => Car <br/> Cap 
     [CSA]  => Jack <br /> Jill 
     [status]  => 3 
    ) 

[2] => Array 
    (
     [customerID] => 1234456 
     [service] => Plate 
     [CSA]  => Jack 
     [status]  => 1 
    ) 

)现在

,如果该服务是在一组,其中在客户是该指数相同的,那么它不应该添加到值字符串。除了CustomerID以外的其他所有情况也是如此。

我该如何用PHP来做到这一点?

回答

0

试试这个,如果你不介意使用客户ID作为数组键输出数组:

$finalArray = array(); // This will be the output array. 
foreach ($mainArray as $subArray) { // Iterate through the multidimensional array. 
    $currentCustomerID = $subArray['customerID']; 
    if (!array_key_exists($currentCustomerID, $finalArray)) { // If the customer hasn't been loaded into the output array yet, load the current array in. 
     $finalArray[$currentCustomerID] = $subArray; 
    } 
    else { // If the customer has already been loaded into the output array, concatenate the service and CSA values. 
     $finalArray[$currentCustomerID]['service'] .= ' <br /> '.$subArray['service']; 
     $finalArray[$currentCustomerID]['CSA'] .= ' <br /> ' . $subArray['CSA']; 
     // Not sure how you want to handle the status, but you can do something like: 
     // if ($subArray['status'] > $finalArray[$currentCustomerID]['status']) { 
     //  $finalArray[$currentCustomerID]['status'] = $subArray['status']; 
     // } 
     // ...or using whatever other conditions you need to handle it. 
    } 

} 
1

您可以控制customerID作为数组键。

基地例如:

$arr = array(/** **/); 

$arrayResult = array(); 

foreach ($arr as $itemResult) { 
    if (!isset($arrayResult[$itemResult['customerID']])) { 
    $arrayResult[$itemResult['customerID']] = $itemResult; 
    continue; 
    } 

    // Adding service 
    $arrayResult[$itemResult['customerID']]['service'] .= '<br />' . $itemResult['service']; 
    // Adding CSA 
    $arrayResult[$itemResult['customerID']]['CSA'] .= '<br />' . $itemResult['CSA']; 
}