0

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',
        ),
    )
3
  • sidenote: array_map(fn($v) => explode(',', $v), $array_1) will work in place of the loop Commented Jan 22, 2022 at 14:46
  • Ok thanks, but do you also know how to fix my problem with the extra array? Commented Jan 22, 2022 at 14:51
  • Just push array 1 to post meta Commented Jan 22, 2022 at 15:01

1 Answer 1

0

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]);

Sign up to request clarification or add additional context in comments.

1 Comment

This is the same as using the first array by itself

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.