Ad

Update Post Meta With Array Without Being Nested

- 1 answer

If convert a comma separated array to a normal array and update the post meta in wordpress, I get an extra nested array layer that I don't need. Does anyone know how to fix this? Or convert the array before updating the post metadata?

$array_1 = array (
  0 => '6801,6800,7310,6795',
);

$array_2 = array();

foreach ($array_1 as $value) {

    array_push($array_2 , explode(",",$value));
}

update_post_meta($post->ID, 'post_meta_field', $array_2);

//print_r($array_2);

}
add_action( 'save_post', 'my_save_post_function', 10, 3 );

It outputs as following:

array (
  0 =>  // I don't need this layer!!
  array (
    0 => 
    array (
      0 => '6801',
      1 => '6800',
      2 => '7310',
      3 => '6795',
    ),
  ),
)

But I need this:

   array (
        0 => 
        array (
          0 => '6801',
          1 => '6800',
          2 => '7310',
          3 => '6795',
        ),
    )
Ad

Answer

Assuming you need all that logic to generate the array in your actual code, you could simply pick out the first element of the outermost array:

update_post_meta($post->ID, 'post_meta_field', $array_2[0]);

Ad
source: stackoverflow.com
Ad