0

我有 Yii 代码作为-

public function actionpublishPollResult()
    {
        $model=new Polloption();
        $json='{"pollId":2}';    
        $obj=json_decode($json);
        $model->pollId=$obj->pollId;
        $options=Polloption::model()->findAllByAttributes(array('pollId'=>$model->pollId));
        $total=0;

        foreach ($options as $option)
        {

            echo "option id :-".$option->optionId."<br>";
            $vote=new Pollvote();
            echo "Number of votes to option :".$option->optionId." "."is=".count($option->pollvotes)."</br>";
            $total=$total+count($option->pollvotes);
            $data[] =count($option->pollvotes);
        }
        echo "</br>";
        echo "Total number of votes obtained=".$total;
        foreach ($data as $votepercentage)
        {
            $percentageResult[]=$votepercentage/$total*100;
        }

        echo "</br>";
        echo CJSON::encode(array('options'=>$options,'percentagevotes'=>$percentageResult));

    }

所以它给了我输出

{"options":[{"optionId"=>1,"option"=>"abc"},{"optionId"=>2,"option"=>"xyz"}],{"percentagevotes":[25 ,75]}}

但我只想在选项数组中添加这个百分比投票字段。那么我需要在上面的 foreach 结构中进行哪些更改。因为 $total 只有在执行整个选项循环后才会获得。所以如何计算和添加百分比投票字段仅在选项的 foreach 中。请指导我...

4

1 回答 1

0

将您的第二个foreach循环编辑为

$toJson=array();
foreach ($data as $i=>$votepercentage)
        {
            $tmp=array();
            $tmp['optionId']=$option[$i]->optionId;
            $tmp['option']=$option[$i]->option;
            $tmp['percentageVote']=$votepercentage/$total*100;
            $toJson[]=$tmp;

        }

然后

  echo CJSON::encode(array('options'=>$toJson));
于 2013-02-04T12:49:23.183 回答