donglang6656 2015-03-10 02:06
浏览 36
已采纳

使用array_count_values()并仍然保持密钥 - PHP

Let's say I have two arrays...

$radicand_array = array(3, 5, 5, 2);
$coeff_array = array(-10, 14, 3, -6);

I'd like to be able to determine which (if any) values in $radicand_array match, AND also know what the keys are. So, in this case I would want to know that there's a match on keys 1 and 2 of $radicand_array.

I need to know this because I want to then add the corresponding key values in $coeff_array. So, in this case I would then add 14 and 3 based on the matching 5's in $radicand_array.

I've tried array_count_values(), but it doesn't seem to give the key values like I want. Is there a PHP function ready made for this?

  • 写回答

2条回答 默认 最新

  • douxingti9307 2015-03-10 02:45
    关注

    Using the link:

    Fixed. Good man!

    <?php
        // $radicand_array = array(3, 5, 5, 2);
        $radicand_array = array(3, 5, 5, 2, 3, 3);
        $coeff_array = array(-10, 14, 3, -6);
    
        $unique = array_unique($radicand_array);
        $duplicates = array_diff_assoc($radicand_array, $unique);
    
        // Duplicate keys
        $aDupes = array_keys(array_intersect($radicand_array, $duplicates));
        $iSum = 0;
        $iCountDupes = count( $aDupes );
        for( $i = 0; $i < $iCountDupes; ++$i )
        {
            if( !empty( $coeff_array[ $aDupes[ $i ] ] ) )
            {
                $iSum = $iSum + $coeff_array[ $aDupes[ $i ] ];
            }
        }
        var_dump( $iSum );
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?