[英]How to convert array and sort elements by categories?
請幫忙。
無法理解如何按數組中的類別對項目進行排序。
我有帶產品的普通數組:
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
是排序鍵,您可以更改它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.