LoginSignup
1
0

More than 5 years have passed since last update.

【PHP】二次元配列から共通要素を取得する

Last updated at Posted at 2018-04-20

たとえばこんな配列があるとする

$c = [[1,2],[2,3],[3,4]];
$d = [[1,2],[3,5],[6,7]];

これらの配列から共通要素([1,2])を取り出したい
配列の共通要素を取得するのに、array_intersect()という関数があるらしいので、
それをつかってみると、

$e = array_intersect($c, $d);
Notice: Array to string conversion in XXX

というエラーメッセージがでて、うまく取得できません
PHPの配列処理に有効な処理方法として、こんなものがありました

foreachは配列を反復処理するための便利な方法です

なので、foreachをつかってみると共通要素がとれました

$common = [];

foreach ($c as $v1) {

    foreach ($d as $v2) {

        if ($v1 == $v2) {

            array_push($common, $v1);

        }

    }

}

print_r($common);
Array ( [0] => Array ( [0] => 1 [1] => 2 ) )
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0