我如何在 yii2 应用程序中提取 json 数据

How do i extract json data in yii2 applaication

我有下面这种形式的数据

var bet_info = [{"country":"ENG ","league":"Premier League 
(GB)","home_team":"Chelsea","away_team":"Tottenham","opt":"W1 ","odds":1.2,"startDate":1605456000}, 
{"country":"ENG ","league":"Premier League (GB)","home_team":"Everton","away_team":"Fulham","opt":"X 
","odds":3.4,"startDate":1605549600}]

然后我使用 ajax

将它发送到服务器
         $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            data: {bet_info:bet_info},
            success: function (data) {  
                $("#smallModal").hide();
                data = jQuery.parseJSON(data);
                console.log(data);
            },
            error: function(jqXHR, errMsg) {
             // handle error
                   $("#smallModal").hide();
                    alert('server error occur. try again later');
                    console.log(errMsg);
            }
        });

在我的控制器中有以下内容

     if (Yii::$app->request->isAjax) {
         $data = Yii::$app->request->post();

         $myArray = json_decode($data['bet_info'], true);
         echo $myArray[0]['home_team'];

         /*also try to decode it as object*/
         $myArray = json_decode($data['bet_info'];
         echo $myArray[0]->home_team;

         /*also try to loop through it as an array*/
          foreach($data['bet_info'] as $betInfo){
            $a[] = $betInfo['home_team'];
         }

         return $a;

     }else{
         throw new ForbiddenHttpException(\Yii::t('app','You\'re not allowed to access this page').'.');
     }

None 上面的尝试对我有用,有时我得到 parseError 如何将数据作为数组或对象获取我可以遍历它以将其保存到数据库 如有任何帮助,我们将不胜感激

这是控制器上的更改代码:

if (Yii::$app->request->isAjax) {
        $data = Yii::$app->request->post();
        $myArray = $data["bet_info"];

        echo $myArray[0]['home_team'];

        /*also try to decode it as object*/
        $myArray = $data['bet_info'];
        echo $myArray[0]['home_team'];

        /*also try to loop through it as an array*/
        foreach($data['bet_info'] as $betInfo){
            $a[] = $betInfo['home_team'];
        }

        return json_encode($a);

    }else{
        throw new ForbiddenHttpException(\Yii::t('app','You\'re not allowed to access this page').'.');
    }

您的 post 数据不是 json 字符串,它是一个数组。所以我们正常获取所有请求数据