【问题标题】:Add parts of a php mysql array together in little bunches? Leave out other parts of same array?将部分 php mysql 数组添加到小束中?省略同一数组的其他部分?
【发布时间】:2011-09-01 05:22:24
【问题描述】:

如何更改下面的代码,以便将每个部分添加在一起而不是混合在一起?如果屏幕上出现的一小部分是 123,它应该添加 12+3 并显示 15 而不是 123。我尝试过 sum_array 和其他东西,但是将 PARTS 与其他 PARTS 以小束的形式添加是行不通的。我只能让它显示下面的混合结果,或者以其他方式添加错误的部分或整个内容。

 $data = mysql_query('SELECT weight FROM my_table WHERE session_id = "' . session_id() . '"'); 
    $params = array();
    while ($row = mysql_fetch_assoc($data)) {     
    $params[] = $row['weight']; 
    }
    $combinations=getCombinations($params);
    function getCombinations($array)
    {
        $length=sizeof($array);
        $combocount=pow(2,$length);
    for ($i=1; $i<$combocount; $i++)
        {
    $binary = str_pad(decbin($i), $length, "0", STR_PAD_LEFT);
            $combination='';
            for($j=0;$j<$length;$j++)
            {
                if($binary[$j]=="1")
                    $combination.=$array[$j];
            }
            $combinationsarray[]=$combination;
     echo $combination . "&lt;br&gt;"; 
        }
        return $combinationsarray;
    } 

【问题讨论】:

  • 我不确定你在做什么。似乎算法是问题,而不是php代码。但是,您的代码中没有“+”,因此不会添加。

标签: php mysql arrays sum add


【解决方案1】:

看起来像

$combination.=$array[$j];

是你的问题。在 PHP 中用于字符串连接而不是数学。因为 PHP 是一种松散的数据类型语言,所以您告诉 PHP 将 $array[$j] 的字符串值和“.=”(追加)它到 $combination 给您 12 .= 3 == "123" 问题和不是 15 喜欢你想要的。您应该尝试使用 +=。

【讨论】:

    【解决方案2】:

    如果我理解您要做什么,我认为您想在以下行中使用加法 + 而不是串联 .

    if($binary[$j]=="1")
        $combination += $array[$j];
    

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 2022-01-24
      • 2011-07-25
      • 2017-11-24
      相关资源
      最近更新 更多