【问题标题】:Laravel PHP return array in a specific wayLaravel PHP以特定方式返回数组
【发布时间】:2021-04-19 19:17:53
【问题描述】:

我正在尝试在 laravel 中将数组返回到 json,以便我可以在视图上构建图表。控制器看起来像这样。

    //Paso 1. Buscar el gráfico asociado a este ID
    $chartset = Chart::findOrFail($chart);

    $q = $chartset->dataset()->first(); //Buscar la pregunta
    $Question = Question::find($q->labels); //Para usar los datos en el arreglo que regresa en JSON

    //Armando los Datos

    //Hace falta asignar el tipo de gráfico
    //Paso 2 Crear el Arreglo para devolver el chart data
    $ChartData = array(    //Arreglo con los parámetros del Chart
        "chart" => array( 
            "title" => $chartset->title, 
            "caption" => $Question->FullLabel, 
            "subcaption" => "February 2016", 
            "captionFontSize" => "24", 
            "paletteColors" => "#A2A5FC, #41CBE3, #EEDA54, #BB423F, #F35685", 
            "baseFont" => "Quicksand, sans-serif", 
            //more chart configuration options
         )
    ); 

    $ChartData["data"] = array(); //Arreglo donde iran los labels 

    //Paso 3, Iterar por cada uno de los datos en el chart

   foreach($chartset->dataset()->get() as $charts){ 
        $ans = Answer::where('AnswerId',$charts->data)  //Obtener Las respueestas
                     ->where('QuestionId',$charts->labels)
                     ->first();

        $responses = DB::table('responses') //Obtener los respondientes que contestaron con esa respuesta
                 ->join('questions', 'responses.QuestionId', '=', 'questions.QuestionId')
                 ->select('questions.FullLabel','responses.QuestionId',DB::raw('responses.Value as Label'),DB::raw('count(responses.Value) as Total'))
                 ->where('responses.QuestionId',$ans->QuestionId)
                 ->where('responses.Value',$ans->Label)
                 ->groupBy('questions.FullLabel','responses.Value','responses.QuestionId')
                 ->get();
      
        foreach($responses as $response){  //Llenar el arreglo con datos
            array_push($ChartData["data"], array( 
                "label" => $response->Label, 
                "value" => $response->Total 
            )); 
        }

   }

    return response()->json($ChartData);

而且返回的值是这样的

{
"chart": {
 "title": "Dashboard Test",
 "caption": "Q062. Ya que vio el anuncio, ¿cómo se siente sobre TABCIN?",
 "subcaption": "February 2016",
 "captionFontSize": "24",
 "paletteColors": "#A2A5FC, #41CBE3, #EEDA54, #BB423F, #F35685",
 "baseFont": "Quicksand, sans-serif"
 },
"data": [
  {
   "label": "-3 La odio",
   "value": 5
  },
  {
   "label": "+3 La amo",
   "value": 127
  },
  {
   "label": "-1",
   "value": 15
  },
  {
   "label": "-2",
   "value": 6
  },
  {
   "label": "0 Neutral",
   "value": 214
  },
  {
   "label": "+2",
   "value": 150
  },
  {
   "label": "+1",
   "value": 85
  }
 ]
}

我想要的是返回的数据看起来像这样。

{
"chart": {
 "title": "Dashboard Test",
 "caption": "Q062. Ya que vio el anuncio, ¿cómo se siente sobre TABCIN?",
 "subcaption": "February 2016",
 "captionFontSize": "24",
 "paletteColors": "#A2A5FC, #41CBE3, #EEDA54, #BB423F, #F35685",
 "baseFont": "Quicksand, sans-serif"
 },
"data": [
  {
   "label": ["-3 La odio","+3 La amo","-1","-2","0 Neutral","+2","+1",],
   "value": [5,127,15,6,214,150,86],
  },
 ]
}

有没有办法像这样返回标签和值数据?

提前致谢,我们将不胜感激。

【问题讨论】:

    标签: php arrays json laravel


    【解决方案1】:

    只需像这样更改构建数据数组的方式

    foreach($responses as $response){  //Llenar el arreglo con datos
        $ChartData["data"]['label'][] = $response->Label;
        $ChartData["data"]['value'][] = $response->Total;
    }
    

    【讨论】:

    • 谢谢先生。这就是我一直在寻找的。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 2012-09-16
    • 2017-02-02
    • 1970-01-01
    • 2018-11-10
    • 2020-01-13
    相关资源
    最近更新 更多