douzi4724 2014-05-27 15:27
浏览 6
已采纳

如果唯一,如何在数组中存储值

I'm writing a PHP report which is designed to be exported purely as a CSV file, using commma delimiters.

There are three columns relating to product_id, these three columns are as follows:

SKU                Parent / Child      Parent SKU
12345                  parent             12345
12345_1                child              12345
12345_2                child              12345
12345_3                child              12345
12345_4                child              12345
18099                  parent             18099
18099_1                child              18099

At the moment the code looks like this:

<?php

    $con_size = array (35,355,36,37,375,38,385,39,395,40,405,41,415,42,425,43,435,44,445,45,455,46,465,47,475,48,485);
    $arrlength=count($con_size);

    for($x=0;$x<$arrlength;$x++) {

    // check if size is available
    if($line['quantity_c_size_'.$con_size[$x].'_chain'] > 0 ) {

      ?>

        <? echo 'Shoes'; ?>,
        <?=$line['product_id']?>,
        ,
        ,

So at the moment this is simply echoing out the product_ID into the SKU column. How would I create an array which tests whether the 'product_id' is unique and if not suffixes the ID with _1, _2, etc.

Thanks,

  • 写回答

2条回答 默认 最新

  • douchongzhang9267 2014-05-27 15:29
    关注

    Test whether it's in the array, and add it if it's not.

    if (!in_array($line['product_id'], $SKU)) {
        $SKU[] = $line['product_id'];
        echo $line['product_id'];
    } else {
        echo $line['product_id'] . "_1";
    }
    

    If you need the suffixes to increment each time, you can do:

    $SKU_counters = array();
    if (isset($SKU_counters[$line['product_id']])) {
        echo $line['product_id'] . "_" . $SKU_counters[$line['product_id']]++;
    } else {
        echo $line['product_id'];
        $SKU_counters[$line['product_id']] = 1;
    }
    

    At the end of the loop you do:

    $SKU = array_keys($SKU_counters);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c