Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 按给定顺序的索引值对数组排序_Php_Arrays_Sorting - Fatal编程技术网

Php 按给定顺序的索引值对数组排序

Php 按给定顺序的索引值对数组排序,php,arrays,sorting,Php,Arrays,Sorting,也许标题没有多大意义,但我实际上想要实现的是使用具有排序值的数组按其索引对数组进行排序: $sortingValues = array( 'category-1', 'category-2', ... 'category-9', ); $categories['category-1'][] = $article; $categories['category-2'][] = $article; ... $categories['category-9'][] = $a

也许标题没有多大意义,但我实际上想要实现的是使用具有排序值的数组按其索引对数组进行排序:

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

我想要实现的是使用$sortingValues中的排序值对$categories进行排序。

我们都知道使用globals是一种不好的做法。为什么不将排序数组传递给函数呢?调用函数的是uksort,它只传递2个键进行比较。
$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"; 
  }
}
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" );