How to add data to OBJECT from WordPress get_results in PHP

Seems really easy, but I can’t seem to figure it out…

I have a simple line that gets mysql results through wordpress like this:

Read More
$sql_results = $wpdb->get_results($sql_phrase);

Then I parse it as JSON and echo it: json_encode($sql_results);

However, I want to add other data before I parse it as JSON. But I’m not sure how.

$sql_results basically gets me a list of post ID’s, title and category.
It looks like this in var_dump (this is just the first row):

array(1)
{
[0]=> object(stdClass)#2737 (7)
    {
    ["ID"]=> string(4) "2700"
    ["post_title"]=> string(18) "The compact helmet"
    ["category"]=> string(5) "Other"
    }
}

Now to start with something easy, I’d like all associative arrays inside the object to have the extra key-value. I tried the following but got an error:
500 Internal error.

foreach($sql_search as $key => $value)
{
    $value['pic_img'] = "test";
    $sql_search[$key]=$value;       
}
$result=$sql_search;

Related posts

2 comments

  1. $sql_results = array(1)
    {
    [0]=> object(stdClass)#2737 (7)
        {
        ["ID"]=> string(4) "2700"
        ["post_title"]=> string(18) "The compact helmet"
        ["category"]=> string(5) "Other"
        }
    }
        foreach($sql_results as $key=>$value)
        { 
            $value->solution = 'good';
            $sql_results[$key]=$value;
    
        }
    $result=$sql_results;
    var_dump($result);
    
  2. $test = array ( array("ID"=>"35", "name"=>"Peter", "age"=>"43"), 
    
    array("ID"=>"34", "name"=>"James", "age"=>"19"), array("ID"=>"31", "name"=>"Joe", "age"=>"40") );
    
        foreach($test as $key=>$value)
        { 
            $value['solution'] = 'good';
            $test[$key]=$value;
    
        }
    $result=$test;
    var_dump($result);
    

Comments are closed.