gpt4 book ai didi

php - 重新排列对象PHP

转载 作者:行者123 更新时间:2023-12-03 01:32:58 26 4
gpt4 key购买 nike

我有一个产品对象列表,看起来像这样:

Product Object
(
[id:private] => 1688115
[categoryId:private] => 1
[merchant:private] => theredshop
[name:private] => Pepsi Max Cans 6 x 375mL
)

每次获取数据,我都会获取15条记录(Im使用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;

关于php - 重新排列对象PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54626167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com