php - 重新排列对象 PHP
问题描述
我有一个产品对象列表,如下所示:
Product Object
(
[id:private] => 1688115
[categoryId:private] => 1
[merchant:private] => theredshop
[name:private] => Pepsi Max Cans 6 x 375mL
)
每次获取数据,我获取 15 条记录(我正在使用 ElasticSearch),对于 15 条记录,产品订单按商家名称排序,因此它将是 1 个商家堆叠在顶部,然后转到下一个商家。
我想要做的是将对象结果订单“洗牌”到至少 1 个商家展示一次,然后再放置另一个商家。例如,这是我当前的结果:
merchant name
theredshop pepsi
theredshop lorem
theredshop ipsum
我想要的是
merchant name
theredshop pepsi
sevel lorem
bluecircle ipsum
我知道如何通过循环和检查已加载的商家名称来安排结果。但是我怎样才能重新安排对象结果呢?还是我应该重新创建对象?
解决方案
假设一个记录表$products
可以这样用 PHP 编写:
// restructure array as merchants having nested record sets
$merchants = [];
foreach(array_unique(array_column($products, 'merchant')) as $merchant)
$merchants[$merchant] = array_values(array_filter($products, function($v)use($merchant){ return $v->merchant === $merchant;}));
// itererate over indexes up do max. products per merchant and a add a product of
// each merchant having a record with that index
$max_count = max(array_map(function($v){return count($v);}, $merchants));
$new_order = [];
for($i = 0; $i<$max_count; $i++)
foreach ($merchants as $merchant)
if($item = $merchant[$i] ?? false)
$new_order[] = $item;
var_dump($new_order);
根据您的评论,您似乎有一个您称为“列表”的对象,如下所示:
$products_object = (object)
[
(object)[
'merchant' => 'theredshop',
'name' => 'pepsi',
],
(object)[
'merchant' => 'sevel',
'name' => 'pepsi',
],
(object)[
'merchant' => 'sevel',
'name' => 'lorem',
],
(object)[
'merchant' => 'sevel',
'name' => 'ipsum',
],
(object)[
'merchant' => 'bluecircle',
'name' => 'ipsum',
],
];
首先将其转换为数组,以便在其上使用数组函数:
$products = (array) $products_object;
推荐阅读
- javascript - UI5 应用安全建议
- javascript - 3D 光线投射 - 光线朝上或朝右时墙壁上出现奇怪的线条
- mql4 - 如何从之字形中识别先前的低点或高点
- sql - 嵌套的 json_agg
- flutter - 如何在同一文件中不存在的两个小部件之间传递文本值
- c# - 我在 KubernetesClient C# 中找不到重启计数
- swift - 有没有办法将最小 macOS 部署目标设置为旧版本但能够在最新的 mac 以及 xcode 上运行?
- android - Web Speech api不适用于android chrome
- matlab - 如何在给定的地方画圆圈?
- python - 如何在 Python 上使用 Selenium 处理下拉菜单?