0

Perhaps the title didn't make much sense, but what I actually want to achieve is to sort an array by its index using an array with the sorting values:

$sortingValues = array(
    'category-1',
    'category-2',
    ...
    'category-9',
);
$categories['category-1'][] = $article;
$categories['category-2'][] = $article;
...
$categories['category-9'][] = $article;

What I want to achieve is to sort $categories with the sorting values in $sortingValues.

2 Answers 2

1
$sortingValues = array( 'category-1', 'category-4', 'category-2', 'category-9');
$categories = array( 'category-1' => 'cat1', 'category-2' =>'cat2', 'category-4' => 'cat4', 'category-9'=>'cat9');

//

foreach($sortingValues as $cat) {
  if(array_key_exists($cat, $categories)) {
   print $categories[$cat] . "\n"; 
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0
function cmp_sortingValues( $a, $b ) {
  global $sortingValues;
  if( $a == $b ) return 0;
  $apos = array_search( $a, $sortingValues );
  $bpos = array_search( $b, $sortingValues );
  return ( $apos>$bpos ) ? 1 : -1;
}

uksort( $categories, "cmp_sortingValues" );

2 Comments

We all know that using globals is bad practice. Why not pass the sorting array to the function instead?
It is uksort that calls your function and it passes only 2 keys for comparison.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.