Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

get data from json array in laravel

I'm starting my studies at LARAVEL and I still have some difficulties, I would like help from the community. I have the following information in the table

id           created_at           updated_at  day         period  temperature
 1  2021-01-22 18:36:58  0000-00-00 00:00:00  2020-12-12  MORNI         36.50
 2  2021-01-22 18:36:58  0000-00-00 00:00:00  2020-11-13  MORNI         33.60
 3  2021-01-22 18:36:58  0000-00-00 00:00:00  2020-10-14  MORNI         32.30
 4  2021-01-22 18:36:59  0000-00-00 00:00:00  2020-12-12  AFTER         37.40
 5  2021-01-22 18:36:59  0000-00-00 00:00:00  2020-11-13  AFTER         36.20
 6  2021-01-22 18:36:59  0000-00-00 00:00:00  2020-10-14  AFTER         34.40
 7  2021-01-22 18:36:59  0000-00-00 00:00:00  2021-01-21  AFTER         29.10
 8  2021-01-22 18:37:00  0000-00-00 00:00:00  2020-12-14  NIGHT         33.90

I need the json exit to be that way (group by period)

      {
     "name":"MORNI",
     "data":[
        {
           "x":"2020-12",
           "y":36.50
        },            {
           "x":"2020-11",
           "y":33.60
        }
     ]
  },
  {
     "name":"AFTER",
     "data":[
        {
           "x":"2020-12",
           "y":37.40
        },etc
     ]
  },
  {
     "name":"NIGHT",
     "data":[
        {
           "x":"2020-12",
           "y":33.90
        },etc
     ]
  }

how to build the controller?

    public function index()
{
    $reg = Climate::orderBy('Day')->get();
    $data = [];
    
    ...
    
    
    return response()->json( $data );
}

I appreciate any help

question from:https://stackoverflow.com/questions/65902988/get-data-from-json-array-in-laravel

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the output pattern you shared can't be done by Eloquent directly. Hope this might help you:

public function index()
{
    $reg = Climate::orderBy('Day')->get();
    $data = [];
    foreach($reg as $item){
        if(!isset($data[$item->period])){
            $data[$item->period]['name'] = $item->period;
            $data[$item->period]['data'] = [];
        }
        array_push($data[$item->period]['data'], ["x" => $item->day, "y" => $item->temperature ]);
    }     
    return response()->json( $data );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...