array_intersect throws errors when arrays have sub-arrays

后端 未结 2 1595
后悔当初
后悔当初 2021-01-16 05:42

I\'m trying to use array_intersect to compare two arrays of arrays.

$start[]=array(
        \'id\'=>1,
        \'name\'=>\'Up\',
        \         


        
相关标签:
2条回答
  • 2021-01-16 05:58

    Someone else elsewhere suggested array_map and serialize. I ended up coming up with this--which is certainly much easier than nesting and recursion and failing miserably in an attempt to basically rewrite the array_intersect function.

    echo '<pre>';
    
    $start[]=array(
            'id'=>1,
            'name'=>'Up',
            'action'=>'up'
    );
    $start[]=array(
            'id'=>3,
            'name'=>'Down',
            'action'=>'down'
    );
    $start[]=array(
            'id'=>5,
            'name'=>'Left',
            'action'=>'left'
    );
    $start[]=array(
            'id'=>2,
            'name'=>'Left',
            'action'=>'left'
    );
    
    
    
    
    
    $end[]=array(
            'name'=>'Up',
            'id'=>1,
    
            'action'=>'up'
    );
    $end[]=array(
            'id'=>8,
            'name'=>'Right',
            'action'=>'Right'
    );
    
    
    
    
    function serialize_array_values($arr){
        foreach($arr as $key=>$val){
            sort($val);
            $arr[$key]=serialize($val);
        }
    
        return $arr;
    }
    
    
    
    
    $result = array_map("unserialize", array_intersect(serialize_array_values($start),serialize_array_values($end)));
    
    echo "\n\n\n";
    echo var_dump($result);
    
    
    echo '</pre>';
    
    0 讨论(0)
  • 2021-01-16 06:11

    The array_diff and array_intersect convert each element in the primary array in to a string for comparison. If you would like a different comparison, then you could use the callback method with the following built-in functions:

    array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
    array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
    array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
    

    I found these by searching PHP.net for the function array_diff and followed the related function links. Its a great way to see alternatives for doing something.

    0 讨论(0)
提交回复
热议问题