Build array from existing array?

I have a function that returns an array of Objects (Wordpress posts, in this case). I want to loop through that array, use the ID from each of the Post Objects, and spit out a new array that includes the Post Thumbnail image (which is gotten with another function get_the_post_thumbnail(‘ID’)).

So I’d start with

[  
  {
    "ID": 1,
    "content":"thecontent"
  },
  {
    "ID": 2,
    "content: "thecontent
  }
]

and end up with

[  
  {
    "ID": 1,
    "content":"thecontent",
    "the_image":"url.com/image1"
  },
  {
    "ID": 2,
    "content: "thecontent,
    "the_image":"url.com/image2"
  }
]

What’s the most efficient way to do this if the query already returns all of the data (except the image url that I need)?

You could use array_map

resultArray = array_map(function(entry) {
  entry->image = getImage(entry->ID);
  return entry;
}, oldArray);

(Sorry but I cannot Format the code correct in my iPad. Do not know what’s wrong)

1 Like

Fixed for you, no worries :slight_smile:

2 Likes

The most efficient way to do this would be to use the Array.map() method. This method allows you to iterate over an array and modify each item in the array. For example, given the array from above, you could do something like this:

let newArray = array.map((postObj) => {
  let newObj = {
    ...postObj,
    the_image: get_the_post_thumbnail(postObj.ID)
  }
  return newObj;
});

This would loop through the original array and create a new object that includes the image url for each post.

I don’t think your code would work well in PHP :wink:

1 Like

I would think that editing the query that fetches the data in the first place, to include the image would be most efficient.
Eg:-

SELECT `ID`, `content`, `etc` FROM `posts`

Becomes:-

SELECT `ID`, `content`, `the_image`, `etc` FROM `posts`

I don’t think that will work… The array I’m starting with is more than just the array of IDs… It’s an array of objects, and I need to use a specific key (‘ID’) from each object as the argument for get_the_post_thumnbail_url($ID)

Why don’t you try it. It works like expected….

I seem to keep breaking something.

get_the_post_thumbnail_url(‘ID’); returns the url that I need to add the array.
$query->$posts is the array of post objects

$query = new WP_Query($args);
$posts = $query->$posts;


$new_array = array_map('get_the_post_thumbnail_url', $posts->ID); 
return $new_array;

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.