php - 对数组进行分组并按相同的键值分配唯一编号
问题描述
我有一个数组,我需要在其中为属于不同零售商的产品分配唯一的批次 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
)
解决方案
步骤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% 为您工作。
推荐阅读
- python - AWS lambda:使用子进程导入外部 python 库使程序太慢
- php - 如何下载 XLXS 或其他可以在最新 MAC 中打开的格式的 HTML 数据
- docker - docker volume over fuse:传输端点未连接
- node.js - 在 api 请求之间保持 mongodb 会话
- vba - 尝试在 Oulook365 中为重复电子邮件运行 VBA 代码时出现运行时错误 438
- javascript - 字符串化Mongoose对象时nodejs“未定义”
- c++ - 我知道 C++ 基础知识,我能找到任何小工作吗?
- json - 是否有任何 API 服务可以过滤掉 json 数据?
- java - 我想从下面的响应中创建一个数组 List。我的列表应该是 Class Temp 类型
- javascript - MongoDB 限制集合大小