I'm trying to add new key => value pairs to an array that I have. The keys are integers that correspond to user IDs. The values would initially just be the string "requested".
The array in question is stored in serialized form at index zero of another array users_attending
in a larger array of metadata related to the post that I am modifying.
My process is like this:
- Pull a variable that might contain the array from a certain WordPress function. If there's no array then that variable is just empty, we wouldn't see an error.
- If the array variable is non-empty and does not contain a key that is equal to the user's ID, then add the key => value pair.
- If the array variable is non-empty and does contain a key that is equal to the user's ID, then print that the user is already there.
- In all other situations (meaning when the array variable is empty) then create a new array and add the first key => value pair.
However, via this process I see all newly added arrays nesting within first array, then the second array, and so on. When I test the contents of the array with print_r($eventUsers)
, I see this kind of output:
Array
(
[0] => Array
(
[0] => Array
(
[4] => requested
)
[4] => requested
)
[4] => requested
)
For context, here is how users_attending
section looks in the larger array of all post metadata (it is automatically serialized by the update_post_meta()
function):
[users_attending] => Array
(
[0] => a:2:{i:0;a:2:{i:0;a:1:{i:4;s:9:"requested";}i:4;s:9:"requested";}i:4;s:9:"requested";}
)
Here's the relevant code:
$currentUser = get_current_user_ID(); //let's say this is 4 for now
$eventUsers = get_post_meta(get_the_ID(), 'users_attending');
if (!empty($eventUsers) && !array_key_exists($currentUser, $eventUsers)) {
$eventUsers[$currentUser] = "requested";
update_post_meta(get_the_ID(), 'users_attending', $eventUsers);
//array exists but user is not yet attending
} elseif (!empty($eventUsers) && array_key_exists($currentUser, $eventUsers)) {
//user is already attending
} else {
$eventUsers = array();
$eventUsers[$currentUser] = "requested";
update_post_meta(get_the_ID(), 'users_attending', $eventUsers); //note that this adds the metadata key and value if it's not already there
//first user attending
}
What can I do to make sure that the key => value pairs are being added to the first array within the zero index of users_attending
instead of this nesting behavior that I am seeing?