Accessing lower values of multilevel array in PHP

I have a PHP array of objects and would like to get all the post_id values easily. I have looked into things like array_values and am not really sure what to do with this. Is the best way to just use a for loop and add each post_id to another array with all the post ids?

Thanks for the help!

Read More
[0] => stdClass Object
    (
        [post_id] => 70242
        [image_id] => 70244
        [large_image] => 0
    )

[1] => stdClass Object
    (
        [post_id] => 70327
        [image_id] => 70339
        [large_image] => 1
    )

[2] => stdClass Object
    (
        [post_id] => 70017
        [image_id] => 70212
        [large_image] => 1
    )

EDIT:
I am getting this array from a WordPress db call:

$q = <<<SQL
    SELECT post_id, image_id, large_image
    FROM $homepage_db
    ORDER BY position;
SQL;

$results = $wpdb->get_results($q);

And then $results is the array above

Related posts

Leave a Reply

3 comments

  1. using foreach

    $post_ids = array();
    foreach($arr as $e) {
      $post_ids[] = $e->post_id;
    }
    

    using array_map

    $post_ids = array_map('get_post_id', $arr);
    function get_post_id($e) {
      return $e->post_id;
    }
    

    I prefer foreach in this case

  2. Easy. Use array_map. Code below; used JSON for your data to test & demonstrate the concept while retaining your example structure:

    //  Set the JSON string for this example.
    $json_string = <<<EOT
    [
        {
            "post_id": "70242",
            "image_id": "70244",
            "large_image": "0"
        },
        {
            "post_id": "70327",
            "image_id": "70339",
            "large_image": "1"
        },
        {
            "post_id": "70017",
            "image_id": "70212",
            "large_image": "1"
        }
    ]
    EOT;
    
    // Decode the JSON string as any array.
    $json_string_decoded = json_decode($json_string);
    
    // Use array_map to return an array telling you what items have 'distancia'.
    $results = array_map(function($value) {
        return $value->post_id;
      }, $json_string_decoded);
    
    // Dump the array to view the contents.
    echo '<pre>';
    print_r($results);
    echo '</pre>';
    

    And the dumped output would be:

    Array
    (
        [0] => 70242
        [1] => 70327
        [2] => 70017
    )