douhoushou8385 2011-01-30 11:01
浏览 15

如何合并这两个数组?

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.

  • 写回答

3条回答 默认 最新

  • doupi6737 2011-01-30 11:03
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本