0
votes

We have a nasty database call using the Wordpress function $wpdb->get_results(SQL).

After receiving the result in PHP, we need to make a few changes to the result.

So can anyone tell me how I can:

1) Remove specific rows from the get_results() returned object.

2) Change the values of the specific columns in specific rows in the returned object.

I.e. if the object returned is $nastyData, we need to:

1) Remove specific rows from $nastyData

2) Change the value of specific columns in specific rows in $nastyData, for example $nastyData->name for a specific row.

Any ideas?

I have thought about makeing get_results() return the data as an array, but that will create problems in other places in our code (where the code expects to receive an object).

Thanks, Mads

1

1 Answers

2
votes

To start with, your "Nasty database call" should be optimized to be less nasty. More specifically, only query the results you want so that you don't have to remove stuff afterwords. This is the best solution.

If you insist on trying to modify the objects, this is a workaround. According to the documentation, when returning objects, they are returned in one of two ways:

OBJECT - result will be output as a numerically indexed array of row objects.

OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be discarded).

So, knowing that the result is an array of objects, we can get to each individual instance using a foreach construct:

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

foreach($results as $index => $result)
{
   // Change name column to FirstName using copy and delete
   $tmp = $result->name;
   unset($result->name);
   $result->FirstName = $tmp;

   // Remove specific row
   if( $result->name == "Tom")
   {
      unset($results[$index]);
   }
}