2012-04-02 12 views
23

İki diziyi karşılaştırmaya çalışıyorum ve sadece her iki dizide var olan değerleri almam ama maalesef, doğru dizi fonksiyonunu bulamıyorum. . PHP iki diziyi karşılaştırır ve eşleşen değerleri almaz

Ben array_diff() fonksiyonu bulundu: http://php.net/manual/en/function.array-diff.php

Ama her iki dizilerin farkı var.

Örnek:

$array1 = array("**alpha**","omega","**bravo**","**charlie**","**delta**","**foxfrot**"); 
$array2 = array("**alpha**","gamma","**bravo**","x-ray","**charlie**","**delta**","halo","eagle","**foxfrot**"); 

Beklenen Çıktı:

$result = array("**alpha**","**bravo**","**charlie**","**delta**","**foxfrot**"); 

cevap

77

Basit, yerine array_intersect() kullanın:

$result = array_intersect($array1, $array2); 
+2

woahhh !!! çok teşekkür ederim efendim!!! Şimdi işime devam edebilirim ... –

+1

100+ @Alix Axel Yaptığım gün – chhameed

+1

Teşekkür ederim çok ... – KNKM

2

Tamam .. Biz dinamik bir num karşılaştırmak için gerekli Ürün adlarının ber ...

Strings karakter sadece Diziler vardır .... çünkü ...

... Orada muhtemelen daha iyi bir yol ... ama bu benim için çalışıyor ....: >}

// Compare Strings ... Return Matching Text and Differences with Product IDs... 

// From MySql... 
$productID1 = 'abc123'; 
$productName1 = "EcoPlus Premio Jet 600"; 

$productID2 = 'xyz789'; 
$productName2 = "EcoPlus Premio Jet 800"; 

$ProductNames = array(
    $productID1 => $productName1, 
    $productID2 => $productName2 
); 


function compareNames($ProductNames){ 

    // Convert NameStrings to Arrays...  
    foreach($ProductNames as $id => $product_name){ 
     $Package1[$id] = explode(" ",$product_name);  
    } 

    // Get Matching Text... 
    $Matching = call_user_func_array('array_intersect', $Package1); 
    $MatchingText = implode(" ",$Matching); 

    // Get Different Text... 
    foreach($Package1 as $id => $product_name_chunks){ 
     $Package2 = array($product_name_chunks,$Matching); 
     $diff = call_user_func_array('array_diff', $Package2); 
     $DifferentText[$id] = trim(implode(" ", $diff)); 
    } 

    $results[$MatchingText] = $DifferentText;    
    return $results;  
} 

$Results = compareNames($ProductNames); 

print_r($Results); 

// Gives us this... 
[EcoPlus Premio Jet] 
     [abc123] => 600 
     [xyz789] => 800 
İlgili konular