doutuan9357 2013-11-20 05:07 采纳率: 100%
浏览 32
已采纳

匹配数组值对(PHP)

I've been battling with this for HOURS and I am completely stuck.

I'm randomly generating numbers and finding their prime factors. For example...

Prime Factors of 420: 2, 2, 3, 5, 7
Prime Factors of 690: 2, 3, 5, 23

I want to highlight the matching pairs and "uncommon" factors separately as I list them out. So, in this case I would want something like...

Prime Factors of 420: 2, 2, 3, 5, 7
Prime Factors of 690: 2, 3, 5, 23

Then the other 2 and the 7 from 420, and the 23 from 690 would be highlighted in red (for example).

I already have the lists of prime factors in arrays ($factor_list_1_old and $factor_list_2_old respectively). I also have the list of common factors in an array ($commons) and a list of the uncommon factors in an array ($uncommons).

I've tried many ways of doing this and nothing seems to work for all scenarios. I can get this scenario to work, but then it fails for something like 420 and 780.

Any ideas?

  • 写回答

5条回答 默认 最新

  • dongtang2376 2013-11-20 06:11
    关注

    My function

    $array1 = array(2, 2, 3, 5, 7);
    $array2 = array(2, 3, 5, 23);
    
    function highlightFactors($factors, $other_factors)
        {
        $result = array();
        foreach ($factors as $factor)
            {
            if (($found_key = array_search($factor, $other_factors)) === false)
                {
                $result[] = array($factor, 'normal');
                }
            else
                {
                $result[] = array($factor, 'bold');
                unset($other_factors[$found_key]);
                }
            }
        return $result;
        }
    
    echo json_encode(highlightFactors($array1, $array2));
    // [[2,"bold"],[2,"normal"],[3,"bold"],[5,"bold"],[7,"normal"]]
    echo json_encode(highlightFactors($array2, $array1));
    // [[2,"bold"],[3,"bold"],[5,"bold"],[23,"normal"]]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?