首页 > 解决方案 > 重新排列对象 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

我知道如何通过循环和检查已加载的商家名称来安排结果。但是我怎样才能重新安排对象结果呢?还是我应该重新创建对象?

标签: phpsymfonyelasticsearch

解决方案


假设一个记录表$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;

推荐阅读