2016-03-21 5 views
2

私はポーリングを作成できるバックエンドを持っています。世論調査では、私はPollQuestionを作成することができます。そしてPollQuestionのために、私は多くのPollAnswerを作成することができます。私は私のコントローラでこのような何かをした場合、私はそう下記の発生数を取得する

Array 
(
    [0] => stdClass Object 
     (
      [answer] => Answer 1 
     ) 

    [1] => stdClass Object 
     (
      [answer] => Answer 2 
     ) 

    [2] => stdClass Object 
     (
      [answer] => Answer 3 
     ) 

    [3] => stdClass Object 
     (
      [answer] => Answer 4 
     ) 

) 

のような出力を見ることができます

$poll = DB::table('poll')->orderBy('id', 'desc')->first(); 
$question = DB::table('poll_question')->where('poll_id', $poll->id)->first(); 
$answers = DB::table('poll_answer')->select('answer')->where('question_id', $question->id)->get(); 

print_r("<pre>"); 
    print_r($answers); 
print_r("</pre>"); 

、上記の投票はPollQuestionに4つの可能な答えを与えられました。

質問を表示するフロントエンドと、各PollAnswerのラジオボタンがあります。彼らが1つを選択して保存すると、私はPollResponseを取得します。私はこの

$pollResponses = DB::table('poll_response')->select('response')->where('poll_id', $poll->id)->get(); 

ような何かをした場合、出力はこの

Array 
(
    [0] => stdClass Object 
     (
      [response] => Answer 1 
     ) 

    [1] => stdClass Object 
     (
      [response] => Answer 4 
     ) 

    [2] => stdClass Object 
     (
      [response] => Answer 4 
     ) 

    [3] => stdClass Object 
     (
      [response] => Answer 2 
     ) 

    [4] => stdClass Object 
     (
      [response] => Answer 3 
     ) 
) 

のようなものであるかもしれないので、私は人々が選択されているものを見ることができます。今、各PollAnswerの可能性について、それに関連するPollResponseの数を数える必要があります。したがって、上記のデータのために、私は

1 = 1 
2 = 1 
3 = 1 
4 = 3 

ような何かを得る必要があり、私はLaravelでこれを行うことができます任意の簡単な方法はありますか、私は、個々のカウントを取得する回答と応答の両方ループする必要があるでしょうか?

おかげ

答えて

2

私はどのlaravel固有のソリューションを知らないが、あなたは常に別のアレイへの回答をプッシュして、新しい配列にPHP関数array_count_values($array)http://php.net/manual/en/function.array-count-values.php)を使用することができます。

$newArray = array(); 
for($i=0; $i < count($pollResponses); $i++){ 
    array_push($newArray, $pollResponses[$i]->response); 
}; 

$count = array_count_values($newArray); 

解答をキーとし、値として出現する回数を2次元配列で返します。

1

あなたがモデルを使用していると仮定すると、あなたは

$polls = Poll::with(['questions.answers'])->get(); 

あなたPoll.phpが

... 
class Poll extends Model{ 
    public function questions(){ 
     return $this->hasMany(Question::class); 
    } 
} 

あなたQuestion.phpがファイルファイルLaravelでこれを行うことができます

... 
class Question extends Model{ 
    public function answers(){ 
     return $this->hasMany(Answer::class); 
    } 
} 

そして、あなたのビューファイル(.blade.phpであると仮定します)

@foreach($polls as $poll) 
    @foreach($poll->questions as $question) 
     {{ $question->title }} 
     <ul> 
      @foreach($question->answers as $answer) 
       <li>{{ $answer->title }} </li> 
      @endforeach 
     </ul> 
    @endforeach 
@endforeach