代码之家  ›  专栏  ›  技术社区  ›  baycisk

重新排列对象php

  •  0
  • baycisk  · 技术社区  · 6 年前

    我有一个产品对象列表,如下所示:

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

    每次获取数据,我都会获取15条记录(我使用ElasticSearch),对于15条记录,产品订单是按商家名称排列的,所以它将是1个商家堆叠在顶部,然后转到下一个商家。

    我要做的是“洗牌”对象结果命令至少一次商家显示,然后放另一个商家下一个。例如,这里是我当前的结果:

    merchant    name
    theredshop  pepsi
    theredshop  lorem
    theredshop  ipsum
    

    我想要的是

    merchant    name
    theredshop  pepsi
    sevel       lorem
    bluecircle  ipsum
    

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Pinke Helga    6 年前

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