【问题标题】:How to store column data as comma separated values when finding duplicate values in another column?在另一列中查找重复值时如何将列数据存储为逗号分隔值?
【发布时间】:2018-12-17 06:12:33
【问题描述】:

如果任何公司的产品都相同,我必须合并或分解子数组值。

预期的输出应该是这样的:

0 => 
array (
    'company' => '1,6'
    'product' => 5,
),

我的数组是:

array (
    0 => 
    array (
        'company' => 1,
        'product' => 5,
    ),
    1 => 
    array (
        'company' => 2,
        'product' => 4,
    ),
    2 => 
    array (
        'company' => 6,
        'product' => 5,
    ),
    3 => 
    array (
        'company' => 2,
        'product' => 3,
    ),
)

我的代码是:

foreach($prSuppliers as $key=>$val){
    if($prSuppliers[$key]['company_master_id']==$val['company_master_id']){
        $contactemaileach = $val['company_master_id'];
        $imp = implode(',', $contactemaileach);
    }
}

【问题讨论】:

  • 好的,你有什么问题?你的代码的结果是什么?它与您想要的有什么不同?此外,您声称的“预期输出”不是有效数组。
  • 我认为$prSuppliers[$key]['company_master_id']==$val['company_master_id']总是为真。
  • 假设预期输出是:'company' => 1,6?
  • @Michel 是的,我说得对。我更正了预期的输出

标签: php csv multidimensional-array merge


【解决方案1】:

implode() 不会成为简单/直接解决方案的一部分。您应该使用产品值分配临时键,以便您可以在每次迭代期间确定您是在处理产品的第一次出现(存储整个子数组)还是随后出现的产品(使用逗号作为胶水)。

完成迭代后,使用array_values() 重新索引数组。

代码:Demo

$array = array (
    0 => 
    array (
        'company' => 1,
        'product' => 5,
    ),
    1 => 
    array (
        'company' => 2,
        'product' => 4,
    ),
    2 => 
    array (
        'company' => 6,
        'product' => 5,
    ),
    3 => 
    array (
        'company' => 2,
        'product' => 3,
    ),
);

foreach ($array as $set) {
    if (!isset($result[$set['product']])) {
        $result[$set['product']] = $set;
    } else {
        $result[$set['product']]['company'] .= ",{$set['company']}";
    }
}
var_export(array_values($result));

输出:

array (
  0 => 
  array (
    'company' => '1,6',
    'product' => 5,
  ),
  1 => 
  array (
    'company' => 2,
    'product' => 4,
  ),
  2 => 
  array (
    'company' => 2,
    'product' => 3,
  ),
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2011-06-18
    • 2014-07-31
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 2012-05-21
    相关资源
    最近更新 更多