4

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?

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
Prakash Poudel
  • 434
  • 1
  • 5
  • 17

3 Answers3

9

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');
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
2
foreach ($currency_info as $currency) {
    $result[$currency['code']] = $currency['name'];
}
Vahe Shak
  • 957
  • 7
  • 19
2

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;
}
Lovepreet Singh
  • 4,792
  • 1
  • 18
  • 36