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は一意になりますが、多くの第2レベルの配列は同じ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 に答える