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条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源