-2

我有一个关于多维数组的简单问题,我想删除任何多余的元素,比如说在我的情况下,[serviceMethod] => PL要来 2 次,我想搜索“PL”,以了解[APIPriceTax]我想要的元素是否有更低的价格保留它并删除数组中的另一个

Array (
    [0] => Array (
                   [carrierIDs] => 150
                   [serviceMethod] => CP
                   [APIPriceTax] =>  30.63 
                   [APIPriceWithOutTax]  28.32 
                   [APIServiceName] =>  Xpresspost USA 
                   [APIExpectedTransitDay]  => 2 
               )
    [1] => Array (
                    [carrierIDs] => 155
                    [serviceMethod] => PL
                    [APIPriceTax] => 84.13
                    [APIPriceWithOutTax] => 73.8
                    [APIServiceName] => PurolatorExpressU.S.
                    [APIExpectedTransitDay] => 1
               )
  [2] => Array (
                    [carrierIDs] => 164
                    [serviceMethod] => PL
                    [APIPriceTax] => 25.48
                    [APIPriceWithOutTax] => 22.35
                    [APIServiceName] => PurolatorGroundU.S.
                    [APIExpectedTransitDay] => 3
                  )

)

这是我的伪代码:$carrierAddedToList实际数组在哪里

$newCarrierAry = function($carrierAddedToList)
  { 
   $newArray = array(); 
   foreach($carrierAddedToList as $cV => $cK) 
   { 
    if( !in_array($cK['serviceMethod'],$newArray) ) 
     { 
       array_push($newArray, $cK['serviceMethod']); 
     } 

   } 
    return $newArray;
 } ; 
  print_r($newCarrierAry($carrierAddedToList));
4

1 回答 1

1

由于没有in_array()搜索多维元素,因此构建一个由 serviceMethod 键入的关联数组。然后您可以使用isset()该方法检查我们是否已经有一个元素。

$newArray = array();
foreach ($carrierAddedToList as $cK) {
    $sm = $cK['serviceMethod'];
    if (!isset($newArray[$sm]) || $newArray[$sm]['APIPriceTax'] > $cK['ApiPriceTax']) {
        $newArray[$sm] = $cK;
    }
}
// Now convert associative array to indexed:
$newArray = array_values($newArray);
于 2013-10-18T21:50:26.123 回答