WordPress.org

Ready to get started?Download WordPress

Forums

Tricky working with array result from $wpdb->get_results (3 posts)

  1. anandg
    Member
    Posted 7 years ago #

    I have a query that has a multidimensional array as a result:

    <?php
    $subpages = $wpdb->get_results("
    SELECT post_title
    FROM $wpdb->posts
    INNER JOIN $wpdb->page2cat
    ON $wpdb->page2cat.page_id = $wpdb->posts.ID
    WHERE $wpdb->page2cat.pagecat_id = 2
    ");
    ?>

    When I view the results of $subpages with print_r() I get this:

    Array
    (
    [0] => stdClass Object
    (
    [post_title] => Test 1
    )
    [1] => stdClass Object
    (
    [post_title] => Test 2
    )
    [2] => stdClass Object
    (
    [post_title] => Test 3
    )
    )

    I find it difficult working with this array, because I can't access the values easy. There is a stdClass Object in each entry of the array. Does anyone know of a way to not get the stdClass Object or how to easily work with such an array?

    For example, it would be easy if I could retrieve the value like $subpages[0] or $subpages['post_title'] as a one dimensional array.

  2. fshuja
    Member
    Posted 7 years ago #

    you can access the array using the following code
    simply loop the $subpage for each stdClass and access the stdClass using the following code

    i=0 to length
    $data = $subpage[i];
    echo $data->post_title;

    Faraz

  3. orvar
    Member
    Posted 7 years ago #

    $subpages = $wpdb->get_results("SELECT [...]", ARRAY_A);

Topic Closed

This topic has been closed to new replies.

About this Topic