Echo part of an array

I have queried the database in WordPress using get_results() and I get the following when I dump the $myrows variable. How do I echo each part?

array(1) {
 [0]=>object(stdClass)#215 (2) {
 ["location_id"]=> string(1) "5"
 ["location_name"]=> string(9) "Liverpool"
 }
}

I would like to be able to have the following the variable dumped is $myrows:

echo '<p>' . $myrows['location-name'] . '</p>';

Related posts

2 comments

  1. What you’re seeing there is an array of objects (within only a single item in that array).

    $obj = $array[0]; // Change the $array to match your variable name
    echo $obj->location_id;
    echo $obj->location_name;
    

    Alternatively, you can update get_results() to return the items as an array of arrays.

    For example:

    $query = "SELECT * FROM $wpdb->posts"; // Change to suit your needs
    $array = $wpdb->get_results( $query, ARRAY_A );
    
    $arr = $array[0]; // Change the $array to match your variable name
    echo $arr['location_id'];
    echo $arr['location_name'];
    

    Typically, you would use get_results() to get multiple rows, so you would use foreach() or something similar:

    $results = $wpdb->get_results( $query, ARRAY_A );
    
    foreach ($results as $row) {
        echo $row['location_id'];
        echo $row['location_name'];
    }
    

    If you only wanted to get a single row, you can use the get_row($query, ARRAY_A) method instead.

    There’s lot of information about the $wpdb class in the WordPress Codex.

  2. if echo part of an array
    foreach($p as $value):
            echo $value['location_name'],"<br>";
    endforeach;
    

    if echo total of an array

    foreach($p as $value):
            foreach($value as $key=>$val)
                echo ">>>>>>>",$key,"=$val<br>";
        endforeach;
    

Comments are closed.