How to convert array to a json object?

后端 未结 1 721
感情败类
感情败类 2021-01-23 08:57

I am trying to push values in an array and it comes like

[{\"Monday\":\"11:30\"},{\"Monday\":\"12:00\"},{\"Monday\":\"23:00\"},{\"Tuesday\":\"11:30\"},{\"Tuesday         


        
相关标签:
1条回答
  • 2021-01-23 09:18

    You may use mapToGroups to get in the requested format. But i don't know your table structure so i got these;

    [{"Monday":"11:30"},{"Monday":"12:00"},{"Monday":"23:00"},{"Tuesday":"11:30"},{"Tuesday":"12:00"},{"Tuesday":"23:00"}]
    

    put into the collection (assuming your eloquent collection returns like that)

    $timings = collect([
            ["Monday" => "11:30"],
            ["Monday" => "12:00"],
            ["Monday" => "23:00"],
            ["Tuesday" => "11:30"],
            ["Tuesday" => "12:00"],
            ["Tuesday" => "23:00"]
        ]);
    
        return $timings->mapToGroups(function ($item) {
            $day = array_key_first($item);
    
            return [$day => $item[$day]];
        });
    

    which prints these;

    {
      "Monday": [
        "11:30",
        "12:00",
        "23:00"
      ],
      "Tuesday": [
        "11:30",
        "12:00",
        "23:00"
      ]
    }
    

    Edit: (the same array you posted in online used here + same function i used for solution)

    $days = ["Monday", "Monday"];
    $time = ["11:30", "12:30"];
    $doctor_timings = [];
    for ($i = 0; $i < sizeof($days); $i++) {
        $day_id = $days[$i];
        $time_id = $time[$i];
        array_push($doctor_timings, [$day_id => $time_id]);
    }
    
    return collect($doctor_timings)->mapToGroups(function ($item) {
        $day = array_key_first($item);
    
        return [$day => $item[$day]];
    });
    

    which prints

    {"Monday":["11:30","12:30"]}
    
    0 讨论(0)
提交回复
热议问题