duanjiwu0324 2018-09-02 00:08
浏览 156
已采纳

如何将字符串数组与数字数组进行比较?

dear users of StackOverflow. There is some problem.

Array 1:
array: 3 [▼
   0 => "8"
   1 => "13"
   2 => "15"
]

Array 2:
array: 16 [▼
   0 => 7
   1 => 8
   2 => 9
]

array_diff does not work, because in the first number, in the second string.

Please suggest any ideas for solving the issue. I will be happy with any comment. Many thanks.

  • 写回答

2条回答 默认 最新

  • doutuo2829 2018-09-02 00:22
    关注

    You can use array_udiff to compare the arrays using a user-defined callback which converts the values to ints before comparing:

    $array1 = array('8', '13', '15');
    $array2 = array(7, 8, 9);
    $diffs = array_udiff($array1, $array2, function ($a, $b) { return (int)$a - (int)$b; });
    print_r($diffs);
    

    Output:

    Array
    (
        [1] => 13
        [2] => 15
    )
    

    Update

    It has been pointed out that the desired output hasn't been specified, so here is how to get all unique values:

    $diffs1 = array_udiff($array1, $array2, function ($a, $b) { return (int)$a - (int)$b; });
    $diffs2 = array_udiff($array2, $array1, function ($a, $b) { return (int)$a - (int)$b; });
    $diffs = array_merge($diffs1, $diffs2);
    print_r($diffs);
    

    Output:

    Array
    (
        [0] => 13
        [1] => 15
        [2] => 7
        [3] => 9
    )
    

    and all matching values using array_uintersect:

    $same = array_uintersect($array1, $array2, function ($a, $b) { return (int)$a - (int)$b; });
    print_r($same);
    

    Output:

    Array
    (
        [0] => 8
    )
    

    Note

    In PHP7 there is now the spaceship operator (<=>) which can also be used in the comparison function e.g.

    $diffs = array_udiff($array1, $array2, function ($a, $b) { return (int)$a <=> (int)$b; });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示