2013-10-18 111 views
-2

我有一個關於多暗數組的簡單問題,我想刪除任何redundent元素讓我們說在我的情況下,[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)); 
+0

你有什麼問題呢? – Barmar

+0

你可以用類似於我在這裏建議的方式嘗試它:http://stackoverflow.com/questions/19423074/skipping-a-multidimensional-array-in-a-foreach-loop-php/19423354#19423354 – CBroe

+0

爲什麼'APIPriceTax'有時會指向一個'SimpleXMLElement'對象,而其他時間只是指向一個數字? – Barmar

回答

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); 
+0

你是一個救生員:) 非常感謝。 – Nadeem