我有一个数组,我想对它进行排序:
$ArrayStock = array(array("SIZE","L","XL","M"),("STOCK","12","3","2"));
如何按“SIZE”对数组进行排序?
或者,我可以使用此数组作为起点:
$ArrayStock = array(array("L","XL","M"),("12","3","2"));
答案 0 :(得分:1)
你可以这样做:
// Combine into one associative array
$combined = array_combine($ArrayStock[0], $ArrayStock[1]);
// Rebuild it in the correct order:
foreach(["SIZE", "S","M","L","XL","XXL"] as $size) {
if (isset($combined[$size])) $result[$size] = $combined[$size];
}
// Split associative array back to its original structure:
$ArrayStock = [array_keys($result), array_values($result)];
请注意,这种结构在使用时并不实用。事实上我会坚持使用关联数组。
答案 1 :(得分:0)
有一些方法可以给这只猫上皮。我的所有方法都会产生预期的输出......
首先,让我们在不重组你的数组(Demo)的情况下这样做:
$order=["XS","S","M","L","XL","2XL","3XL"]; // declare appropriate size order
$ArrayStock=[["L","XL","M"],["12","3","2"]];
// Order the first subarray:
uasort($ArrayStock[0],function($a,$b)use($order){
return (array_search($a,$order)>array_search($b,$order)?1:-1); // any unidentifed sizes will go to the front
});
// Sync the second subarray with first subarray:
$ArrayStock[1]=array_replace($ArrayStock[0],$ArrayStock[1]);
// Optionally re-index the keys:
$ArrayStock[0]=array_values($ArrayStock[0]);
$ArrayStock[1]=array_values($ArrayStock[1]);
接下来,我将展示一些可以操作重组数组的方法。 trincot写出他的方式绝对没有错。这些只是我提出的替代方案......
我同意使用尺寸作为键(因为它们将是唯一的)并且库存计为值的trincot。所以第一个过程是生成新的数组结构:
$ArrayStock=[["L","XL","M"],["12","3","2"]];
#1 单行array_combine()
方法:
$new_structure=array_combine($ArrayStock[0],$ArrayStock[1]);
// $new_structure = ['L'=>'12','XL'=>'3','M'=>'2']
#2 foreach()
方法:
foreach($ArrayStock[0] as $i=>$size){
$new_structure[$size]=$ArrayStock[1][$i];
}
// $new_structure = ['L'=>'12','XL'=>'3','M'=>'2']
现在要对新数组进行排序,您可以使用uksort()
或一系列其他数组函数/循环与预定的顺序数组:
$order=["XS","S","M","L","XL","2XL","3XL"]; // declare whatever appropriate sizes in order
采用uksort()
方法的 #1 array_search()
:
uksort($new_structure,function($a,$b)use($order){
return (array_search($a,$order)>array_search($b,$order)?1:-1);
// any unidentified sizes will go to the front of the array
});
// keep in mind, this doesn't declare $result, it sorts $new_structure
#2 array_replace()
array_flip()
- array_intersect()
- array_keys()
方法:
$result=array_replace( // replace values on matching keys
array_flip( // swap keys with values
array_intersect(
$order, // keep values from here
array_keys($new_structure) // that exist here
)
),
$new_structure); // use these elements for replace
// $result=['M'=>'2','L'=>'12','XL'=>'3'];
#3 foreach()
array_intersect()
- array_keys()
方法:
// generate & iterate ordered array
foreach(array_intersect($order,array_keys($new_structure)) as $v){
$result[$v]=$new_structure[$v]; // build properly sorted array
}
// $result=['M'=>'2','L'=>'12','XL'=>'3'];
最后,正如trincot所示,你可以将已排序的数据恢复为初始格式,再添加一行:
$ArrayStock=[array_keys($result),array_values($result)];