VVV
VVV

Reputation: 7593

Merging multiple objects

I have a MYSQL query the goes through a framework (WolfCMS).

$sql_query = 'SELECT DISTINCT country FROM ' . $tableName . ' ORDER BY country ASC';
$countries = Record::query($sql_query, array()); //execute query

But what is returned is an array of objects like this

Array ( [0] => stdClass Object ( 
        [country] => Canada ) [1] => stdClass Object ( 
        [country] => France ) )

I was wondering if there was a way with php to merge all the object to get the array as simple as possible like

Array ( [0] => Canada  [1]  => France )

I know I could always parse the array with a foreach loop once I get the data and create a custom array the way I needed but I was wondering if there was a way to directly get the data to it's final form from the database.

I just want a simple array to use it as an parameter for an autocomplete function on a text field.

* EDIT *

I found a better way. I simply had to avoid executing the query with the Record class.

Here's how

//create sql statement
$sql_query = 'SELECT DISTINCT country' . 
            ' FROM ' . Record::tableNameFromClassName(__CLASS__) . 
            ' ORDER BY country ASC';
$stmt = Record::getConnection()->prepare($sql_query);
$stmt->execute(array());
return $stmt->fetchAll(Record::FETCH_COLUMN);

Upvotes: 1

Views: 111

Answers (2)

SWilk
SWilk

Reputation: 3464

Have you tried array_map?

$countries = array_map(function ($item) { return $item->country; }, $result );

Upvotes: 1

Yotam Omer
Yotam Omer

Reputation: 15366

You'll not be able to achieve this with only a query in WolfCMS. You should try:

$finalArr = array();
for($i=0; $i<sizeof($result);$i++) // $result being your query result
    array_push($finalArr,$result[$i]->country);

print_r($finalArr);

Upvotes: 1

Related Questions