-1

I use the PHP code below to update the post meta. My goal is to extend the current post meta with a new array. The problem is that I get a lot of nested arrays that stay at [0]. It should continue counting the arrays.

My PHP code:

$my_array =   // This changes every time
   array(
   'name' => 'Name 3',
   'amount' => '30',
   'date' => '2019-09-28',
   'message' => 'Test 3',);

$get_post_meta = get_post_meta('33300', 'test_post_meta');

$combine_arrays = $get_post_meta + $my_array;

update_post_meta('33300', 'test_post_meta', $combine_arrays);

The post meta output is this:

array ( // The arrays are all nested
  0 => 
  array (
    0 => 
    array (
      0 => 
      array (
        'name' => 'Name 1',
        'amount' => '10',
        'date' => '2019-09-26',
        'message' => 'Test 1',
      ),
      'name' => 'Name 2',
      'amount' => '20',
      'date' => '2019-09-27',
      'message' => 'Test 2',
    ),
    'name' => 'Name 3',
    'amount' => '30',
    'date' => '2019-09-28',
    'message' => 'Test 3',
  ),
)

While it should be like this:

array ( // It should look like this and count
  0 => 
      array (
        'name' => 'Name 1',
        'amount' => '10',
        'date' => '2019-09-26',
        'message' => 'Test 1',
      ),
  1 => 
    array (
      'name' => 'Name 2',
      'amount' => '20',
      'date' => '2019-09-27',
      'message' => 'Test 2',
    ),
 2 => 
  array (
    'name' => 'Name 3',
    'amount' => '30',
    'date' => '2019-09-28',
    'message' => 'Test 3',
  ),
)

Any ideas how to solve this? The counting of the arrays has to go automatically.

Bob
  • 415
  • 6
  • 15

1 Answers1

0

Ok I found it out myself. Problem was that I had to merge on the [0] level.

This is the solution:

$array = array (
    'test' => // This will change every time
    array (
      0 => 'Value 0',
      1 => 'Value 1',
      2 => 'Value 2',
      3 => 'Value 3',
    ),
  );

  $get_post_meta = get_post_meta('33300', 'test_post_meta');
  $result = array_merge($get_post_meta[0], $array); // Merge on the [0] level.

  update_metadata( 'post', '33300', 'test_post_meta', $result); // Update merged array
Bob
  • 415
  • 6
  • 15