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:
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?
The program looks ok, try deleting the data from previous runs.
Also consider the function get_post_meta maybe returns an array of arrays instead of the array you want.