首页 > 解决方案 > 对数组进行分组并按相同的键值分配唯一编号

问题描述

我有一个数组,我需要在其中为属于不同零售商的产品分配唯一的批次 ID

foreach($data as $type){
$grouped_types[$type['retailer']][] = $type;
}

$data 是我的数组

Array
 ( 
[1] => Array
    (

        [productid] => 1001
        [mrp] => 444
        [whpoid] => 105
        [retailer] => HYD-48AC
        [manufacturerbarcode] => 
        [comments] => 
        [lastmodifiedby] => 
        [lastmodifieddate] => 2019-02-12 11:49:19
    )

[2] => Array
    (
        [productid] => 1002
        [mrp] => 444
        [whpoid] => 106
        [retailer] => HYD-48AC
        [manufacturerbarcode] => 
        [comments] => 
        [lastmodifiedby] => 
        [lastmodifieddate] => 2019-02-12 11:49:19
    )

[3] => Array
    (
        [productid] => 1003
        [mrp] => 444
        [whpoid] => 105
        [retailer] => HYD-48AC
        [manufacturerbarcode] => 
        [comments] => 
        [lastmodifiedby] => 
        [lastmodifieddate] => 2019-02-12 11:49:19
    )
 [4] => Array
    (
        [productid] => 1005
        [mrp] => 444
        [whpoid] => 105
        [retailer] => PUN-48AC
        [manufacturerbarcode] => 
        [comments] => 
        [lastmodifiedby] => 
        [lastmodifieddate] => 2019-02-12 11:49:19
    )

预期输出因此数组 2 和 3 属于同一零售商,因此它们具有相同的批次 id。我需要为每个不同的零售商分配唯一的批次 id,但同一零售商下的产品应该具有相同的批次 id。请帮助。提前致谢

Array
 ( 
  [1] => Array
  (

    [productid] => 1001
    [mrp] => 444
    [whpoid] => 105
    [retailer] => HYD-48AC
    [manufacturerbarcode] => 
    [comments] => 
    [lastmodifiedby] => 
    [lastmodifieddate] => 2019-02-12 11:49:19
    [batchid] => B001
  )

  [2] => Array
  (
    [productid] => 1002
    [mrp] => 444
    [whpoid] => 106
    [retailer] => HYD-48AC
    [manufacturerbarcode] => 
    [comments] => 
    [lastmodifiedby] => 
    [lastmodifieddate] => 2019-02-12 11:49:19
    [batchid] => B002
  )

 [3] => Array
   (
    [productid] => 1003
    [mrp] => 444
    [whpoid] => 105
    [retailer] => HYD-48AC
    [manufacturerbarcode] => 
    [comments] => 
    [lastmodifiedby] => 
    [lastmodifieddate] => 2019-02-12 11:49:19
    [batchid] => B002
   )
  [4] => Array
  (
    [productid] => 1005
    [mrp] => 444
    [whpoid] => 105
    [retailer] => PUN-48AC
    [manufacturerbarcode] => 
    [comments] => 
    [lastmodifiedby] => 
    [lastmodifieddate] => 2019-02-12 11:49:19
    [batchid] => B003
  )

标签: phpmysqlarrays

解决方案


步骤1

以零售商数组的键值对为例,如下所示

//Where key as retailer id and value as batch id
$retailers = array(
     "HYD-48AC" => "B001",
     "PUN-48AC" => "B001",
); 

现在在你的 foreach 循环中应用以下逻辑

foreach($data as $type){
    $batch_id = $retailers[$type['retailer'];
    $type['batchid'] = $batch_id;
    $grouped_types[$type['retailer']][] = $type;
}

这将 100% 为您工作。


推荐阅读