我有一个产品对象列表,看起来像这样:
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
我知道如何通过循环和检查已加载的商人名称来安排结果。但是如何重新排列对象结果呢?还是我应该重新创建对象?
答案 0 :(得分:1)
假设一个记录表$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;