I have an array of objects and I need to convert to key value pairs, my code is
i have a model as: model setting.php
public function currency_info(){
$currency_info = [
['code' => 'AED', 'name' => 'United Arab Emirates Dirham'],
['code' => 'ANG', 'name' => 'NL Antillian Guilder'],
['code' => 'ARS', 'name' => 'Argentine Peso'],
['code' => 'AUD', 'name' => 'Australian Dollar'],
['code' => 'BRL', 'name' => 'Brazilian Real'],
]
}
and controller as:
SettingController.php
public function index()
{
$setting = new Setting();
$currency_list = $setting->currency_info();
$result = [];
foreach ($currency_list as $currency) {
$result[$currency->code] = $currency->name;
}
return $result;
}
i get the following error:
ErrorException (E_NOTICE) Trying to get property 'code' of non-object
Where am I doing wrong and how can I correct this?
As the data your trying to iterate over is an array (from an object) the notation should be...
$result[$currency['code']] = $currency['name'];
Or if you want a shorter version (depends on version of PHP), use array_column()...
$result = array_column($currency_list, 'name', 'code');
foreach ($currency_info as $currency) {
$result[$currency['code']] = $currency['name'];
}
currency_info
function return array, so treat it as array. You are using $currency->code
to access code
key from array, use as $currency["code"]
instead.
public function index() {
$setting = new Setting();
$currency_list = $setting->currency_info();
$result = [];
foreach ($currency_list as $currency) {
$result[$currency["code"]] = $currency["name"];
}
return $result;
}