如何解决基于数组键的PHP产品多维数组排序
我有一个数组$data['products'][] = array()
,它从数据库中获取数据。现在,我想根据[catname]
对这个数组进行排序。
将所有类似的[catname]
进行分组/排序。对于前。所有与仙人掌有关的产品都将是第一,然后是特殊糖果
我的阵列
$data['products'][] = array(
'product_id' => $result['product_id'],'name' => $result['name'],'catname' => $result['catname'],'description' => utf8_substr(trim(strip_tags(html_entity_decode($result['description'],ENT_QUOTES,'UTF-8'))),$this->config->get('theme_' . $this->config->get('config_theme') . '_product_description_length')) . '..','price' => $price,);
我尝试使用usort()
function build_sorter($key) {
return function ($a,$b) use ($key) {
return strnatcmp($a[$key],$b[$key]);
};
}
usort($array,build_sorter('catname'));
foreach ($array as $item) {
echo $item['product_id'] . ',' . $item['catname'] . "\n";
}
,但未按需要排序。请帮助纠正此错误。
当前阵列
Array
(
[0] => Array
(
[product_id] => 119
[name] => Product 1
[catname] => Special Sweets
[description] => This is a sweet
[price] => $0.00
)
[1] => Array
(
[product_id] => 56
[name] => Product 2
[catname] => cactus
[description] => description goes here..
[price] => $0.00
)
[2] => Array
(
[product_id] => 59
[name] => Product 3
[catname] => Special Sweets
[description] => Corn goes here con..
[price] => $0.00
)
[3] => Array
(
[product_id] => 79
[name] => Product 4
[catname] => cactus
[description] => cactus goes here con..
[price] => $0.00
)
)
所需阵列
Array
(
[0] => Array
(
[product_id] => 56
[name] => Product 2
[catname] => cactus
[description] => description goes here..
[price] => $0.00
)
[1] => Array
(
[product_id] => 79
[name] => Product 4
[catname] => cactus
[description] => cactus goes here con..
[price] => $0.00
)
[2] => Array
(
[product_id] => 119
[name] => Product 1
[catname] => Special Sweets
[description] => This is a sweet
[price] => $0.00
)
[3] => Array
(
[product_id] => 59
[name] => Product 3
[catname] => Special Sweets
[description] => Corn goes here con..
[price] => $0.00
)
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。