dpkt31779 2015-06-27 00:13
浏览 34
已采纳

2个数组:只保留具有不同值的元素

I have 2 arrays:

Array
(
    [0] => Array
        (
            [id] => 1
            [fieldname] => banana
            [value] => yellow
        ) 
)

Array
(
    [0] => Array
        (
            [id] => 1
            [fieldname] => rome
            [value] => city
        )

    [1] => Array
        (
            [id] => 2
            [fieldname] => bla
            [value] => yes
        )
)

I want to create a new array that contains only elements where "id" is different. In other words I want to get this output:

Array
(
    [0] => Array
        (
            [id] => 2
            [fieldname] => bla
            [value] => yes
        )

)

[id] => 2 was the only different [id] so I keep it.

Said that I've already managed to achieve my goal with an inefficient pile of foreach, if statements and temp variables. I really don't want to use a wall of code for this very small thing so I started to look for a native PHP function with no success. What's the easiest way to get the result? Is it possible that I strictly need to use a foreach with so many if?

  • 写回答

2条回答 默认 最新

  • douzhe9075 2015-06-27 01:18
    关注

    You can use array_udiff with a function.

    Computes the difference of arrays by using a callback function for data comparison.

    Returns an array containing all the values of the first array that are not present in any of the other arguments.


    The code:

    // Setup two arrays as per your question
    $array1 = array (
    
      '0' => array (
        'id' => '1',
        'fieldname' => 'banana',
        'value' => 'yellow',
      )
    
    );
    
    $array2 = array (
    
      '0' => array (
        'id' => '1',
        'fieldname' => 'rome',
        'value' => 'city',
      ),
    
      '1' => array (
        'id' => '2',
        'fieldname' => 'bla',
        'value' => 'yes',
      )
    
    );
    
    // Setup the callback comparison function
    function arrayCompare($array2, $array1) {
        return $array2['id'] - $array1['id'];
    }
    
    // Use array_udiff() with the two arrays and the callback function
    $arrayDiff = array_udiff($array2, $array1, 'arrayCompare');
    print_r($arrayDiff);
    

    The above code returns the following:

    Array (
    
      [1] => Array (
        [id] => 2
        [fieldname] => bla
        [value] => yes
      )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数