简体   繁体   English

如何合并这两个数组?

[英]How to merge these two arrays?

How to merge these two arrays... 如何合并这两个数组...

$arr1 = array(
    [0] => 'boofoo',
    [1] => '2'
);

$arr2 = array(
    [0] => 'fbfb',
    [1] => '6'
);

to get a third array as follows?: 得到第三个数组如下:

$arr3 = array(
    [0] => 'boofoo',
    [1] => '6'
);

That is, preserve strings that are longer and numeric values that are higher. 即,保留较长的字符串和较高的数值。

If both arrays have the same keys, you can do a simple foreach and pick the better value according to their relationship regarding > and strlen respectively: 如果两个数组具有相同的键,则可以执行简单的foreach并根据分别与>strlen有关的关系来选择更好的值:

$arr3 = array();
foreach ($arr1 as $key => $val) {
    if (array_key_exists($key, $arr2)) {
        if (is_numeric($val)) {
            $arr3[$key] = max($val, $arr2[$key]);
        } else {
            $arr3[$key] = strlen($val) > strlen($arr2[$key]) ? $val : $arr2[$key];
        }
    }
}

Before you ask: expr1 ? expr2 : expr3 在您问: expr1 ? expr2 : expr3 expr1 ? expr2 : expr3 is the conditional operator where the expressions expr2 or expr3 are evaluated based on the return value of expr1 . expr1 ? expr2 : expr3是条件运算符 ,其中基于expr1的返回值对表达式expr2expr3进行求expr1 So if strlen($val) > strlen($arr2[$key]) is true, the conditional operation evaluates $val , and $arr2[$key] otherwise. 因此,如果strlen($val) > strlen($arr2[$key])为true,则条件运算的结果$val ,否则$arr2[$key]

I think you can achieve via http://www.php.net/manual/en/function.array-walk.php . 我认为您可以通过http://www.php.net/manual/en/function.array-walk.php来实现。

I try and write some test for it soon and update post. 我会尝试为此编写一些测试并更新帖子。

PS: array_map is better(maybe walk not even good for this?) PS: array_map更好(也许步行甚至不行吗?)

<?php

function combine($arr1, $arr2) {
    return array_map("callback", $arr1, $arr2);
}

function callback($item, &$item2) {
    if (is_numeric($item)) {
        return max($item, $item2);
    }
    if (strlen($item2) > strlen($item)) {
        return $item2;
    }
    return $item;
}

class Tests  extends PHPUnit_Framework_TestCase {
    public function testMergingArrays() {
        $arr1 = array(
            'boofoo',
            '2'
        );

        $arr2 = array(
            'fbfb',
            '6'
        );

        $arr3 = array(
            'boofoo',
            '6'
        );

        $this->assertEquals($arr3, combine($arr1, $arr2));
    }
}

I got test in place and I could refactor it now. 我已经进行了测试,现在可以重构它了。 But this implementation does work. 但是这种实现确实有效。

您可以使用array_merge()函数,然后再进行sort()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM