I have created a new user meta data called 'hca_recent'. I am pulling the data from an ajax call and adding it as an array to the meta data.
$hca_recent_array = array(
'recent_count' => $new_recent_count,
'post_id' => $post_id,
'video_id' => get_post_meta($post_id, "__cvm_video_id", true),
'post_title' => $_REQUEST['post_title'],
'video_url' => $_REQUEST['data_url'],
);
$hca_recent = update_user_meta(get_current_user_id(), "hca_recent", $hca_recent_array);
This outputs the following array:
Array
(
[recent_count] => 42
[post_id] => 667
[video_id] => 881950864
[post_title] => Receiver Blocking: COD + Dots Drill | Tee Martin
[video_url] => https://player.vimeo.com/video/881950864?h=e9b41820da&autoplay=0&muted=0&loop=0&title=1&byline=1&portrait=1&color&dnt=0&background=0&transparent=0
)
That's all well and good. When another ajax call is triggered, I want to add to this array. This is where the problem occurs. I get the existing user meta like such:
$hca_recent_array_old = get_user_meta(get_current_user_id(), 'hca_recent', false);
I then want to merge the existing array with the new ajax call event.
$result_array = array_merge($hca_recent_array_old, $hca_recent_array);
$hca_recent = update_user_meta(get_current_user_id(), "hca_recent", $result_array);
And I get this output:
Array
(
[0] => Array
(
[recent_count] => 42
[post_id] => 667
[video_id] => 881950864
[post_title] => Receiver Blocking: COD + Dots Drill | Tee Martin
[video_url] => https://player.vimeo.com/video/881950864?h=e9b41820da&autoplay=0&muted=0&loop=0&title=1&byline=1&portrait=1&color&dnt=0&background=0&transparent=0
)
[recent_count] => 43
[post_id] => 695
[video_id] => 881950748
[post_title] => Tee Martin | Youth Coaching Keys to Success
[video_url] => https://player.vimeo.com/video/881950748?h=d3b0944767&autoplay=0&muted=0&loop=0&title=1&byline=1&portrait=1&color&dnt=0&background=0&transparent=0
)
I need this array to merge properly with [0], [1], [2] etc. Any help is greatly appreciated.
Every option to merge or recreate the array.
The issue is that you are saving the array as a string in the user meta table and then when you read it, you are merging a new array with a string value (representing an array, but still a string), which results in an array that you showed.
The solution is to save the array in meta table in a different format, for example JSON. It will allow you to parse it into a valid array after reading it.
Here's an example.
Save your array like this:
This will result in something similar to be saved in your table:
Then, read it like this:
and then you can update meta like this: