首页 > 解决方案 > 如何按类别转换数组和排序元素?

问题描述

请帮忙。

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

我有简单的产品数组:

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"
  }
}

标签: phparrays

解决方案


尝试:

foreach($array as $value){
    $newArray[$value["categories_name"]][] = $value;
}
print_r($newArray);

推荐阅读