2012-11-08 150 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']; 
}