如何修改json文件和foreach循环结构

时间:2013-02-04 12:15:31

标签: json foreach yii

我有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));

    }

所以它给我的输出为

{ “选项”:[{ “optionId”=大于1, “选项”=&gt; “中ABC”},{ “optionId”=大于2, “选项”=&gt; “中的xyz”}], { “percentagevotes”:[25,75]}}

但我想只在options数组中添加这个percentagevotes字段。那么我需要在上面的foreach结构中做出哪些改变。因为只有在执行了整个循环选项后才会获得$ total。那么如何仅在选项的foreach中计算和添加percentagevotes字段。请指导我......

1 个答案:

答案 0 :(得分: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));