Saul Martínez
Saul Martínez

Reputation: 920

Sorting an array by index value with given order

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.

Upvotes: 0

Views: 264

Answers (2)

piotrm
piotrm

Reputation: 12356

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" );

Upvotes: 0

busypeoples
busypeoples

Reputation: 737

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

Upvotes: 1

Related Questions