Search code examples
phparrayslaravelobjectkeyvaluepair

how to convert array of objects to key value pairs in php


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?


Solution

  • 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');