简体   繁体   中英

PHP Sort associative array based on array values

I currently have an associative array of values that I need sorted based on values in another array.

Example:

If I have an array of values, AssocArray = '122'=>'12', '123'=>'32', '232'=>'54', '343'=>'12'

I need to check it against another array of values, orderArray = '232', '123'

if it exists then push the value to the top of the AssocArray. so the final array looks like this.

AssocArray = '232'=>'54', '123'=>'32', '122'=>'12', '343'=>'12'

Sorry I do not have any working code, I am still learning PHP.

Any help would be really grateful :) Thank you.

Loop through your $orderArray , and check if an element with that key is present in $AssocArray . If it is, add that element to the $result array, and remove it from the original $AssocArray . Then, you just have to merge the remaining elements in $AssocArray with whatever was pushed to the top of the $results array:

$AssocArray = array( '122'=>'12', '123'=>'32', '232'=>'54', '343'=>'12');
$orderArray = array( '232', '123');

rsort( $orderArray, SORT_STRING); // Make sure the order array is sorted from highest to lowest

$result = array();
foreach( $orderArray as $key) {
    if( isset( $AssocArray[ $key ])) {
        $result[$key] = $AssocArray[ $key ];
        unset( $AssocArray[ $key ]);
    }
}

foreach( $AssocArray as $k => $v) {
    $result[$k] = $v;
}

print_r( $result); // Print the resulting array

You can see that this prints :

Array
(
    [232] => 54
    [123] => 32
    [122] => 12
    [343] => 12
)
$orderArray = array("232", "123");

function customSort($key1, $key2){
    $key1Pos = array_search($key1, $orderArray);
    $key2Pos = array_search($key2, $orderArray);
    if($key1Pos !== NULL && $key2Pos != NULL){
        return $key1Pos - $key2Pos;
    }else if($key1Pos === NULL){
        return 1;
    }else{
        return -1;
    }
}


uksort($array, "customSort");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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