phpsorting

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


If certain elements are contained in an array, I want them moved to the start of it. At first I used a bunch of array_diff_keys to get it to work, but I wanted something more elegant. So I tried using uksort with a callback, but perhaps I'm doing it wrong because it's not working.

I tried this, it's a method of my helper class, but it's not working.

$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;
}

Solution

  • Fairly quick and dirty but here you go.

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

    Assuming I understood what you wanted to do. Example output: for your verification.