doushi8187 2013-10-09 21:58
浏览 27

压缩关联的php数组

Assume the following array in PHP:

array('red','blue','green','purple');      

I would like the simplest and fasted method to make that array come out like this:

array('red'=>'blue','green'=>'purple');      

If there is a php function that already exists that does this, that would be even better. I'm running a php 5.4 and 5.5 both so there hopefully shouldn't be a problem.

  • 写回答

5条回答 默认 最新

  • dongma0722 2013-10-09 22:16
    关注

    Not necessarily the fastest approach, but perhaps it'll introduce a few people to some features of PHP that they weren't aware of before:

    $isEven = function ($value) {
        return !($value & 1);
    };
    
    $isOdd = function ($value) {
        return $value & 1;
    };
    
    function keyfilter($values, $function) {
        return array_intersect_key(
            $values,
            array_filter(
                array_keys($values),
                $function
            )
        );
    }
    
    $colourArray = array('red','blue','green','purple');
    
    $mi = new MultipleIterator(
        MultipleIterator::MIT_NEED_ANY | 
        MultipleIterator::MIT_KEYS_ASSOC
    );
    $mi->attachIterator(
        new ArrayIterator(
            keyfilter(
                $colourArray, $isEven
            )
        ),
        'key'
    );
    $mi->attachIterator(
        new ArrayIterator(
            keyfilter(
                $colourArray, $isOdd
            )
        ),
        'value'
    );
    
    $newColourArray = array();
    foreach($mi as $details) {
        $newColourArray[$details['key']] = $details['value'];
    }
    
    var_dump($newColourArray);
    
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)