【问题标题】:Compare two arrays in a github-style以 github 样式比较两个数组
【发布时间】:2022-10-14 20:35:56
【问题描述】:

我有两个数组(按字母顺序排序),有些值匹配,有些不匹配,双方:

$src = ["apple", "cherry", "grape", "lemon", "orange", "strawberry"];
$dst = ["apple", "banana", "cherry", "orange", "pear"];

我想输出两个列表,因为它们是 github 风格的文件比较,如下所示:

1.apple         1.apple
2.              2.banana
3.cherry        3.cherry
4.grape         4.
5.lemon         5.
6.orange        6.orange
7.              7.pear
8.strawberry    8.

我一直在寻找正确的方法来做到这一点:好的,我为两个数组都做了一个foreach 循环,然后......然后呢?

<ul>
<?php foreach($src as $src_item) : ?>
    <li><?php echo $src_item; // what else??? ?></<li>
<?php endforeach; ?>
</ul>

请问有什么帮助吗? 提前致谢

【问题讨论】:

    标签: php arrays list


    【解决方案1】:

    您可以简单地组合数组唯一项(然后重新排序!)然后您可以循环新数组并检查哪些项在原始 2 个数组中。

    <?php
    
    $src = ["apple", "cherry", "grape", "lemon", "orange", "strawberry"];
    $dst = ["apple", "banana", "cherry", "orange", "pear"];
    
    $combined_items = array_unique(array_merge($src, $dst));
    sort($combined_items);
    
    $new_array = [];
    
    foreach($combined_items as $item){
        $item1 = in_array($item, $src) ? $item : null;
        $item2 = in_array($item, $dst) ? $item : null;
        $new_array[] = [$item1, $item2];
    }
    
    // $new_array will contain ["apple","apple"], [null, "banana"], etc.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 2017-07-23
      • 1970-01-01
      • 2010-12-11
      • 2012-12-26
      • 2021-03-21
      相关资源
      最近更新 更多