2012-06-04 75 views
0

这些都没有工作......(没有排序)为什么这个php array_multisort没有按预期工作?

我改编了这些来自PHP文档网站的例子。

class ProductHelper { 

    function sortProductsByPrice($products, $sort = SORT_ASC) { 
     foreach ($products as $key => $row) { 
      $name[$key] = $row['name']; 
      $rrp[$key] = $row['rrp']; 
     }  
     array_multisort($rrp, $sort, $name, SORT_ASC, $products); 
    } 

    function sortProductsByName($products, $sort = SORT_ASC) { 
     foreach ($products as $key => $row) { 
      $name[$key] = $row['name']; 
     } 
     array_multisort($name, $sort, $products); 
    } 

} 

这是如何我使用它:

 $products = $cur_prod_cat["products"]; // copy an array of products 
     $PRODUCT_HELPER->sortProductsByName($products); //sort it 

在你需要看的情况下,产品阵列看起来是这样的:

Array (
    [0] => Array (
     [id] => 0 
     [name] => product name 
     [description] => product description 
     [price] => product price 
     [etc] => other attributes 
    ) 
    [1] => Array (
     [id] => 1 
     [name] => product name 
     [description] => product description 
     [price] => product price 
     [etc] => other attributes 
    ) 
) 

回答

1

您需要return $rrp在你的第一个和return $name在你的第二个,在你致电array_multisort后。

这是因为该函数正在排序变量$rrp$name,而不是您最初传递给该函数的变量。

编辑:如果你只是想排序$products通过它的name数组值,完全是一个更好的方法如下:

function sort_name($a,$b) { 
    return strcmp($a['name'],$b['name']); 
} 

$products = $cur_prod_cat["products"]; 
usort($products,'sort_name'); 

它使用功能sort_name来确定放哪一个元素的数组中第一。

然后,您可以根据需要创建更多sort_{value}函数,只需更改其包含的字段值即可。

+0

但是,这只会返回一列?另外,不要把$ products数组放在array_multisort函数中对$ products数组进行排序? – Ozzy

+0

如果你看看php.net函数的定义:'bool array_multisort(array&$ arr [,mixed $ arg = SORT_ASC [,mixed $ arg = SORT_REGULAR [,mixed $ ...]]])' - 这是第一个被引用并因此排序的变量,而不是其他值。 – Death

+0

好的。我也刚刚意识到最后一个参数被添加到通过公共密钥进行排序。但是,如果我想对这些列进行排序,那么返回一个完整的产品数组,这意味着我必须复制每一列,对它们进行排序,然后将它们粘在一起? – Ozzy

相关问题