首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在yii2中删除Json数组中的值

如何在yii2中删除Json数组中的值
EN

Stack Overflow用户
提问于 2018-06-01 03:26:05
回答 1查看 289关注 0票数 -1

我有Json数组

代码语言:javascript
复制
{"dashboard_layout":[10,9]}

根据id,我必须从这个数组中删除这些值。

这是我的函数,我添加了我的视图页面,还添加了.Always (失败)部分.Is此函数中的某些错误

代码语言:javascript
复制
  public function actionDelete() {
    if (isset($_POST['id'])) {
        $id = $_POST['id'];
        $model = \app\models\UserPreferences::find()->where(['user_id' => Yii::$app->user->identity->user_id])->one();
        $blockvalues = json_decode($model->others);
        foreach ($blockvalues as $key => $value) {
            if ($value == $id) {
                unset($blockvalues[$key]);
                echo Json::encode([
                    'status' => true,
                ]);
            }
        }
    } else {
        echo Json::encode([
            'status' => false,
            'id'=>$id
        ]);
    }
}



    jQuery('body').on('click', '#delete', function(e) {
  var id=$(this).val();
    alert(id);
      $.ajax({
            type: 'POST',
            cache: false,
            data:{'id': id},
            url: '".Yii::$app->getUrlManager()->createUrl("/dashboard-blocks/delete")."',
            dataType: 'json',
            success: function(data){ 
              alert('hii');
            },
            error: function (xhr, ajaxOptions, thrownError) {
               alert('failed');
            }
        });
});

注意:$model->其他包含json {"dashboard_layout":10,9}

EN

回答 1

Stack Overflow用户

发布于 2018-06-02 05:20:21

代码语言:javascript
复制
public function actionDelete() {
    if(isset($_POST['id'])) {
        $id = $_POST['id'];
        $model = \app\models\UserPreferences::find()->where(['user_id' => Yii::$app->user->identity->user_id])->one();
        // check here if model is not null 
        $perferencesOther = json_decode($model->others);            

        if(!empty($perferencesOther) && isset($perferencesOther->dashboard_layout)) {
            $dashboardLayout = [];       
            foreach ($perferencesOther->dashboard_layout as $key => $value) {                    
                if($value != $id){
                    $dashboardLayout[] = $value;                      
                }
            } 

            $perferencesOther->dashboard_layout = $dashboardLayout;                
            // store updated preferencves in db
            $model->others = json_encode($perferencesOther); 
            $model->save();

            echo Json::encode([
                'status' => true,
                'value'=>$model->others
            ]);                
        }          
    } else {
        echo Json::encode([
            'status' => false,              
        ]);
    }
}

这对我很管用

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50631450

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档