Home > Software engineering >  PHP prepend object in array of objects
PHP prepend object in array of objects

Time:11-22

I have this array $post_types with objects:

Array
(
  [vegetables] => WP_Post_Type Object
    (
        [name] => sports
        [label] => Sports
        [taxonomies] => Array
            (
                [0] => country
                [1] => type
            )

        [has_archive] => 1
        [show_in_rest] => 1
    )

    [fruits] => WP_Post_Type Object
      (
          [name] => fruits
          [label] => Fruits
          [taxonomies] => Array
              (
                  [0] => color
                  [1] => taste
                  [2] => origin
              )
          [has_archive] => 1
          [show_in_rest] => 1
      )
)

And I want to prepend the object from array $prepend into it:

Array
(
  [post] => WP_Post_Type Object
    (
        [name] => post
        [label] => Post
        [taxonomies] => Array
            (
                [0] => categories
                [1] => tags
            )

        [has_archive] => 1
        [show_in_rest] => 1
    )
)

I tried the following:

$post_types[] = $prepend

This adds it to the end of the $post_types array and it wraps an array with index 0 around it like so:

[0] => Array
  (
    [post] => WP_Post_Type Object
    ...
   )
...

I also tried array_unshift($post_types , $prepend);

It adds it to the beginning, but again wraps it in array. How can I add

[post] => WP_Post_Type Object
  (
    [name] => post
    [label] => Post
    ...

to $post_types without having the [0] => array( ... wrapped around [post] => WP_Post_Type Object ... ?

I also tried array_unshift($post_types, array_column($prepend, 'post')) but adds an empty array.

CodePudding user response:

You should be able to "simply" merge the two arrays:

$post_types = array_merge($prepend, $post_types);
  • Related