PHP數組的交集array_intersect(),array_inter_key()等函數的小問題_PHP教程

來源:互聯網
上載者:User
求兩個數組的交集問題可以使用array_intersect(),array_inersect_assoc,array_intersect_key來實現,其中array_intersect()函數是求兩個數的交集,返回一個交集共有元素的數組(只是數組值得比較)、array_intersect_assoc()函數是將索引值和值綁定,一起比較交集部分、array_intersect_key()函數是將兩個數組的索引值進行比較,返回索引值交集的數組。

  但實際應用中也遇到了一些小問題,正如下:

  執行個體:


"Red","green"=>"red4","Red15"=>"Red",7=>"Level","Width"=>"Red","azzzz1"=>"art","peak"=>158); $array1 = array("red"=>"Red2","greena"=>"red","Red15"=>"Red",7=>"Level","Width"=>"Red","azzzz"=>"art","peak"=>158); $num = array_intersect($array,$array1); print_r ($num); echo "
"; $num = array_intersect_assoc($array,$array1); print_r($num); echo "
"; $num = array_intersect_key($array,$array1); print_r ($num); ?>
  運行結果:


Array ( [red] => Red [Red15] => Red [7] => Level [Width] => Red [azzzz1] => art [peak] => 158 ) Array ( [Red15] => Red [7] => Level [Width] => Red [peak] => 158 ) Array ( [red] => Red [Red15] => Red [7] => Level [Width] => Red [peak] => 158 )
  總結:

    1.array_intersect()函數進行的比較只有數組值的比較,而且存在如”Red“和”Red2“比較時會返回"Red",反之則不會返回"Red2";

    2.array_intersect_assoc()函數是將數組的值與索引值一起比較,而且不會存在array_intersect的情況,適用於較嚴格的比較;

    3.array_intersect_key()函數適用於比較兩個數組索引值的交集,返回的並不只有索引值,而是索引值和對應的數組值。

http://www.bkjia.com/PHPjc/478803.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/478803.htmlTechArticle求兩個數組的交集問題可以使用array_intersect(),array_inersect_assoc,array_intersect_key來實現,其中array_intersect()函數是求兩個數的交集,返回一個交...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.