0

我想尝试合并和排序一个多维数组。目前该数组如下所示:

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 将是唯一的,但是,许多二级数组具有相同的 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 为索引的集合中服务相同,则不应将其添加到值字符串中。除了 CustomerID 之外的所有其他内容也是如此。

我如何用 PHP 做到这一点?

4

2 回答 2

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'];
}
于 2012-11-08T20:12:52.040 回答
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.
    }

}
于 2012-11-08T20:13:18.637 回答