繁体   English   中英

如何在PHP中将某些元素提升到数组的开头

[英]How to Promote certain elements to the start of an array in PHP

如果某个元素包含在数组中,我希望它们移动到它的开头。 起初我使用了一堆array_diff_keys来使它工作,但我想要更优雅的东西。 所以我尝试使用带回调的uksort,但也许我做错了因为它不起作用。

我试过这个,这是我的helper类的一种方法,但它不起作用。

$good_elements = array('sku','name','type','category','larping');
$test_array = array('sku','name','asdf','bad_stuff','larping','kwoto');
$results = helper::arrayPromoteElementsIfExist($test_array,$good_elements,false);

public static function arrayPromoteElementsIfExist($test_array,$promote_elements,$use_keys = false) {
    foreach(array('test_array','promote_elements') as $arg) {
        if(!is_array($$arg)) {
            debug::add('errors',__FILE__,__LINE__,__METHOD__,'Must be array names',$$arg);
            return false;
        }
    }
    if(!$use_keys) {
        $test_array = array_flip($test_array); // compare keys
        $promote_elements = array_flip($promote_elements); // compare keys
    }
    uksort($test_array,function($a,$b) use($promote_elements) {
        $value1 = intval(in_array($a, $promote_elements));
        $value2 = intval(in_array($b,$promote_elements));           
        return $value1 - $value2;           
    });
    if(!$use_keys) {
        $test_array = array_flip($test_array);
    }
    return $test_array;
}

相当快速和肮脏,但你去。

function promoteMembers($input, $membersToPromote)
{
    $diff = array_diff($input, $membersToPromote);
    return array_merge($membersToPromote, $diff);
}

假设我明白你想做什么。 示例输出: 供您验证

暂无
暂无

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

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