PHP Multidimensional Arrays - Remove Duplicates

后端 未结 1 1497
深忆病人
深忆病人 2021-01-07 04:21

if anyone could please help me here I would be eternally grateful as I\'ve spent about 2 full days now trying to get this to work. I want to take two multidimensional arrays

相关标签:
1条回答
  • 2021-01-07 05:25

    I don't know how to do it with any built-in PHP function but here's a custom one:

    $array1 = array(
      array( 'id' => 3, 'name' => 'Eye Colour' ),
      array( 'id' => 1, 'name' => 'Hair Colour' ),
      array( 'id' => 5, 'name' => 'Hair Length' ),
      array( 'id' => 4, 'name' => 'Height' ),
    ); 
    
    $array2 = array(
      array( 'attribute_id' => 3, 'name' => 'Eye Colour', 'active' => 1 ),
      array( 'attribute_id' => 5, 'name' => 'Hair Length', 'active' => 1 )
    );
    
    // function to remove duplicates
    function myArrayDiff($array1, $array2) {
        // loop through each item on the first array
        foreach ($array1 as $key => $row) {
            // loop through array 2 and compare
            foreach ($array2 as $key2 => $row2) {
                if ($row['id'] == $row2['attribute_id']) {
                    // if we found a match unset and break out of the loop
                    unset($array1[$key]);
                    break;
                }
            }
        }
    
        return array_values($array1);
    }
    
    $array3 = myArrayDiff($array1, $array2);
    
    print_r($array3);
    
    /* result:
        Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Hair Colour
                )
    
            [1] => Array
                (
                    [id] => 4
                    [name] => Height
                )
    
        )
    */
    
    0 讨论(0)
提交回复
热议问题