开发者

How to merge these two arrays?

开发者 https://www.devze.com 2023-02-07 17:59 出处:网络
How to merge these two arrays... $arr1 = array( [0] => \'boofoo\', [1] => \'2\' ); $arr2 = array( [0] => \'fbfb\',

How to merge these two arrays...

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

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

to get a 开发者_C百科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:

$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 is the conditional operator where the expressions expr2 or expr3 are evaluated based on the return value of expr1. So if strlen($val) > strlen($arr2[$key]) is true, the conditional operation evaluates $val, and $arr2[$key] otherwise.


I think you can achieve via http://www.php.net/manual/en/function.array-walk.php.

I try and write some test for it soon and update post.

P.S: array_map is better(maybe walk not even good for this?)

<?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.


You can use the array_merge() function followed by a sort()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号