根据条件在 php 中搜索并删除多维数组中的元素


Search and remove an element in mulit-dimentional array in php depending on a criteria

我有一个关于多dim数组的简单问题,我想删除任何多余的元素,比如说在我的情况下,[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));

由于没有搜索多维元素的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);