合并和排序PHP多维数组

时间:2012-11-08 20:05:00

标签: php arrays multidimensional-array

我想尝试合并和排序多维数组。目前阵列看起来像这样:

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可能与状态相同。

我希望end数组看起来如下:

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执行此操作?

2 个答案:

答案 0 :(得分: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'];
}

答案 1 :(得分: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.
    }

}