suchen

Heim  >  Fragen und Antworten  >  Hauptteil

php - 求这个两个数组的差集?

Array ( [0] => Array ( [id] => 11 [parametername] => 参数名称11 ) )

Array ( [0] => Array ( [id] => 6 [parametername] => 参数名称6 ) [1] => Array ( [id] => 10 [parametername] => 参数名称10 ) [2] => Array ( [id] => 11 [parametername] => 参数名称11 ) [3] => Array ( [id] => 15 [parametername] => 参数编辑 ) [4] => Array ( [id] => 16 [parametername] => 参数20 ) )

阿神阿神2776 Tage vor674

Antworte allen(3)Ich werde antworten

  • ringa_lee

    ringa_lee2017-04-10 14:56:20

    $array1 = array(
        array('n3'=>'v3', 'n4'=>'v4'),
        array('n1'=>'v1', 'n2'=>'v2')
    );
    
    $array2 = array(
        array('n1'=>'v1', 'n2'=>'v2')
    );
    
    $result = array_udiff(
        $array1,
        $array2,
        function ($v1, $v2) {
            return strcmp(serialize($v1), serialize($v2));
        }
    )
    
    // 或者
    
    $result = array_filter($array1, function($v) use ($array2) {
        return in_array($v, $array2);
    });
    

    你可以试试。

    Antwort
    0
  • PHPz

    PHPz2017-04-10 14:56:20

    回调是你的好朋友。

    数据:

    <?php
    $array1 = array(
        array( "id" => 11, "parametername" => "PARAMETER NAME XI" ) , 
        array( "id" => 30, "parametername" => "PARAMETER NAME XXX" ) , 
    );
    $array2 = array(
        array( "id" => 6, "parametername" => "Parameter Name VI" ), 
        array( "id" => 10, "parametername" => "Parameter Name X" ) , 
        array( "id" => 11, "parametername" => "Parameter Name XI" ) , 
        array( "id" => 15, "parametername" => "Parameter Name XV" ) , 
        array( "id" => 16, "parametername" => "Parameter Name XVI" ) , 
    );
    

    比较代码如下:

    array_udiff($array2, $array1, function($a, $b) {
        return ($a['id'] - $b['id']);
    });
    /*
    array(
        array( "id" => 6, "parametername" => "Parameter Name VI" ), 
        array( "id" => 10, "parametername" => "Parameter Name X" ) , 
        array( "id" => 15, "parametername" => "Parameter Name XV" ) , 
        array( "id" => 16, "parametername" => "Parameter Name XVI" ) , 
    )
    */
    
    array_udiff($array1, $array2, function($a, $b) {
        return ($a['id'] - $b['id']);
    })
    /*
    array(
        array( "id" => 30, "parametername" => "PARAMETER NAME XXX" ), 
    )
    */
    

    另外我希望没理解错题意。以上代码均认为只要id相同就属于同一个数据。如果有必要自行更改回调的逻辑。

    Antwort
    0
  • 迷茫

    迷茫2017-04-10 14:56:20

    回调很好。。学了一招。

    Antwort
    0
  • StornierenAntwort