php - 如何按类别转换数组和排序元素?
问题描述
请帮忙。
无法理解如何按数组中的类别对项目进行排序。
我有简单的产品数组:
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);
推荐阅读
- google-cloud-platform - 使用 gsutil 仅上传 html 文件?
- matlab - 如何在Matlab中以有效的方式将一个值分配给对象列表?
- react-native - React native 或 Flutter 是否支持按需资源?
- react-native - 在 react native expo 应用程序中使用 Formik 时出错
- javascript - 使用 jQuery 的 attr("src", url) 在 iframe 中加载 url 时尝试捕获
- sql - 在多行满足连接条件的情况下随机连接
- git - 如何在本地查看自己在 Gogs 中的文件?
- python - python代码如何与Ionic 4集成
- xslt - xslt 字符串替换为 substring-after
- r - 在圆形条形图(ggplot2)的中心设置图例