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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化