Home > Mobile >  Remove array from array inside get_option
Remove array from array inside get_option

Time:03-02

So I'm using the WordPress get_option() to get my database option of an array of users.

So I have the following method:

    public function deauthorize_instagram_via_button()
    {
        if (!get_option('instagram_authenticated_users')) {
            return;
        }
        $users = get_option('instagram_authenticated_users');
        
        // If we have single entry, delete the option from the database
        if (count($users) === 1) {
            delete_option('instagram_authenticated_users');
            $this->instagram->delete_cache();
        }

        // This returns the user_id
        var_dump($_POST['user_id']);
        die();

        // delete_option('instagram_authenticated_users');
        exit;
    }

Where get_option('instagram_authenticated_users') returns:

array(2) {
  [0]=>
  array(5) {
    ["username"]=>
    string(9) "sem_test1"
    ["user_id"]=>
    int(17841400835712753)
  }
  [1]=>
  array(5) {
    ["username"]=>
    string(12) "sem_test2"
    ["user_id"]=>
    int(17841449642220098)
  }
}

Then I have a $_POST['user_id'] which returns user_id => 17841449642220098.

How can I search through the array and remove that user_id's array and then call update_option('instagram_authenticated_users') so that I keep just one single array inside the array.

So after it gets remove, the get_option('instagram_authenticated_users') will look like this when called:

array(2) {
  [0]=>
  array(5) {
    ["username"]=>
    string(9) "sem_test1"
    ["user_id"]=>
    int(17841400835712753)
  }
}

Thanks all!

CodePudding user response:

You can use array_filter like below:

// get current list
$users = get_option('instagram_authenticated_users');

// filter out POST user id
$filtered_users = array_filter($users, function($user){
    return $user["user_id"] !== (int) $_POST['user_id'];
});

// save filtered array
update_option('instagram_authenticated_users', $filtered_users);
  • Related