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

时间:2018-05-31 19:26:05

标签: jquery ajax yii2

我有Json数组

{"dashboard_layout":[10,9]}

基于id我必须删除此数组中的值。

这是我的功能。我也添加了我的视图页面。总是提醒(失败)部分。这个功能错误了

  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]}

2 个答案:

答案 0 :(得分:0)

您正在使用json_decode('{"dashboard_layout":[10,9]}')将返回

stdClass Object
(
    [dashboard_layout] => Array
        (
            [0] => 10
            [1] => 9
        )

)

所以你应该迭代

foreach ($blockvalues->dashboard_layout as $key => $value) {

或使用将返回数组的yii\helpers\Json::decode('{"dashboard_layout":[10,9]}')

Array
(
    [dashboard_layout] => Array
        (
            [0] => 10
            [1] => 9
        )

)

然后你应该迭代

foreach ($blockvalues['dashboard_layout'] as $key => $value) {

EDIT

所以你的代码应该是

 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->dashboard_layout as $key => $value) {
            if ($value == $id) {
                unset($blockvalues[$key]);
                echo Json::encode([
                    'status' => true,
                ]);
            }
        }
    } else {
        echo Json::encode([
            'status' => false,
            'id'=>$id
        ]);
    }
}

EDIT 2

有一件事我没有更新你的代码,我发现错误发生的原因,我不得不将unset($blockvalues[$key]);更改为unset($blockvalues->dashboard_layout[$key]);

另一件事是,查看代码时,您似乎试图从id表的列中保存为json的dashboard_layout索引中删除所选的UserPreferences { {1}},所以只是取消设置json数组只会帮助你,因为它只取消设置数组索引而你没有将数组更新回表列。

如果以上情况属实,那么您应该在others循环内或检查内添加以下内容

foreach

更新后,您的代码将如下所示

$model->others=json_encode($blockvalues);
$model->save();

答案 1 :(得分:0)

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,              
        ]);
    }
}

这对我有用