Skip to content
Advertisement

Make post_id as the key for my next array

So I’m trying to figure out this small piece, but I’m completely stuck and could use some assistance. I will break the code down into sections for understanding.

This will grab 5 of my posts:

$post_list = get_posts([
    'post_type' => 'post',
    'posts_per_page' => 5,
]);

Output per post:

Array
(
    [0] => WP_Post Object
        (
            [ID] => 59343
        )
)

Then I’m adding the returned ID’s into an array using the below code:

$post_authors = [];
foreach ($post_list as $key => $post) {
    $post_author = get_post_author($post->ID);
    $post_authors[] = $post_author['ID'];
}
print_r($post_authors);

This outputs me the following array:

Array
(
    [0] => 52714
    [1] => 0
    [2] => 3339
    [3] => 0
    [4] => 0
)

Then I’m matching my custom post author meta associated with the post:

$test_id = [];
foreach ($post_authors as $author) {
    $test_id[] = get_post_meta($author, '_test_id');
}
print_r($test_id);

This is the output that I get:

Array
(
    [0] => Array
        (
            [0] => 7899
        )

    [1] => 
    [2] => Array
        (
            [0] => 3487
        )

    [3] => 
    [4] => 
)

Is there a way that I can map the above posts as keys and then have the id as outputs? Also skip the empty values on get_posts().

For example:

Array
(
    [52714] => 7899
    [3339] => 3487
)

All help would be appreciated!

Advertisement

Answer

If I understand your question correctly then you can use this logic.

  $posts = array(5676,6767,0,0,564,898);
    $test_id = [];
    foreach ($posts as $key =>$value) {
        $test_id[$value] = $key; // get_post_meta($author, '_test_id');
    }
    print_r($test_id);

//output

Array
(
    [5676] => 0
    [6767] => 1
    [0] => 3
    [564] => 4
    [898] => 5
)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement