如何转换数组并按类别对元素进行排序



请提供帮助。

无法理解如何按数组中的类别对项进行排序。

我有产品的普通阵列:

Item 1 (Category C)
Item 2 (Category B)
Item 3 (Category A)
Item 4 (Category C)
Item 5 (Category B)
Item 6 (Category A)

并希望按类别对列表进行排序,例如:

Category A
Item 3
Item 6
Category B
Item 2
Item 5
Category C
Item 1
Item 4

原始数组类似于以下内容:

array(4) {
[0]=>
array(19) {
["product_name"]=> "Samsung GALAXY Note 3"
["categories_id"]=> "3"
["categories_name"]=> "Smartphones"
}
[1]=>
array(19) {
["product_nam"]=> "Samsung GALAXY Note 8"
["categories_id"]=> "2"
["categories_name"]=> "Tablets"
}
[2]=>
array(19) {
["product_nam"]=> "Samsung GALAXY Tab 3"
["categories_id"]=> "3"
["categories_name"]=> "Smartphones"
}
[3]=>
array(19) {
["product_name"]=> "Samsung ATIV Smart PC"
["categories_id"]=> "1"
["categories_name"]=> "Laptops"
}
}

尝试:

foreach($array as $value){
$newArray[$value["categories_name"]][] = $value;
}
print_r($newArray);
// First group items by categories
$groupedData = [];
foreach ($originalArray as $item) {
$categoryID = $item['categories_id'];
if (!isset($groupedData[$categoryID])) {
$groupedData[$categoryID] = [
'name' => $item['categories_name'],
'items' => [],
];
}
$groupedData[$categoryID]['items'][] = $item['product_name'];
}
// Next you can sort $groupedData with sorting functions
// Then output data
foreach ($groupedData as $array) {
echo $array['name'] . ':<br />';
foreach ($array['items'] as $item) {
echo $item . '<br />';
}
}

试试这个函数:

/**
* Creates custom array map from 2-dimensional $arr with predefined structure, changing its keys by value, which is present in second dimension.
* 
* @param array $arr 2-dimensional array, which should be mapped, basing on subarray value
* @param string $targetKey Subarray key name. Value, which corresponds to this key, will be set as key in 1st dimension, and this 1st-dimensional key will correspond to subarray
* @param boolean $add If TRUE, every res. arr val represented as indexed list of subarrays. Otherwise every res. arr val contains one sub. arr 
* @return array Mapped arr | original arr, if $targetKey wasn't found in any subarray
*/
public static function setKeyFromVal($arr, $targetKey, $add = false)
{
$mappedArr = [];
foreach ($arr as $subArr) {
if (array_key_exists($targetKey, $subArr)) {
if ($add) {
$mappedArr[$subArr[$targetKey]][] = $subArr;
} else {
$mappedArr[$subArr[$targetKey]] = $subArr;
}
unset($mappedArr[$subArr[$targetKey]][$targetKey]);
}
}
return empty($mappedArr) ? $arr : $mappedArr;
}

调用它(带有true参数!(:

setKeyFromVal($a, 'categories_id', true);

categories_id是一个排序键,您可以更改它

最新更新