我想使用php对数据库行(数组)进行2次排序。首先排序一列,然后在第一排序安排中排序第二种。
我在$ result
中存储了一行Array
(
[0] => Array
(
[brand] => nike
[product] => 1020
)
[1] => Array
(
[brand] => adidas
[product] => 1008
)
[2] => Array
(
[brand] => nike
[product] => 1010
)
[3] => Array
(
[brand] => adidas
[product] => 1001
)
[4] => Array
(
[brand] => nike
[product] => 1018
)
}
我首先排序品牌,订单没有必要,但我只需要组合在一起,我收到一个排序结果,如
Array
(
[4] => Array
(
[brand] => nike
[product] => 1018
)
[0] => Array
(
[brand] => nike
[product] => 1020
)
[2] => Array
(
[brand] => nike
[product] => 1010
)
[1] => Array
(
[brand] => adidas
[product] => 1008
)
[3] => Array
(
[brand] => adidas
[product] => 1001
)
}
现在我需要按行键按升序排序,但在每个品牌中,我想要的结果看起来像这样
Array
(
[0] => Array
(
[brand] => nike
[product] => 1020
)
[2] => Array
(
[brand] => nike
[product] => 1010
)
[4] => Array
(
[brand] => nike
[product] => 1018
)
[1] => Array
(
[brand] => adidas
[product] => 1008
)
[3] => Array
(
[brand] => adidas
[product] => 1001
)
}
我设法实现了这样的结果
$result = original row unaltered/sorted
//create brand array for column data also preserving row key
foreach($rows as $array => $row)
{
$brand[$array] = $row['brand'];
}
//sort_natural here irrelevant, this is just to group together brands
arsort($brand, SORT_NATURAL);
$brand_count = array_count_values($brand);
$unique_brands = array_unique($brand);
//I separate the brand array by each brand, whilst also maintaining row keys, and put them in a multidimensional array
foreach($unique_brands as $key => $value)
{
$i = 1;
while($i <= $brand_count[$value])
{
$sorted_brands[$value][key($brand)] = current($brand);
next($brand);
$i++;
}
}
//sort row keys we preserved which represent the original row ascendingly
foreach($sorted_brands as $key => $value)
ksort($sorted_brands[$key], SORT_ASC);
//now I put all this back into 1 array
foreach($sorted_brands as $multi)
foreach($multi as $key => $value)
$final[$key] = $value;
现在这给我们留下了结果
Array
(
[0] => nike
[2] => nike
[4] => nike
[1] => adidas
[3] => adidas
)
我现在使用这些键为订单创建一个新数组,并引用旧的原始数组来加载相应的值
foreach($final as $key => $value)
$complete[$key] = $result[$key];
这会产生预期的结果,但是说到这一切,我想知道它们是否是一种更简单,更简单的方法来实现这一点,我尝试使用诸如array_multisort,array_column,array_values和其他一些函数实现这一结果。无法到达任何地方。
提前感谢您的建议/帮助。
答案 0 :(得分:0)
因为您的数据行具有相同的结构和大小,所以您只需调用sort()
(Demo)
sort($array);
var_export($array);
这将按行先按brand
值,然后按product
值将行按字母顺序排列。