douxian9706
2018-08-01 07:08
浏览 684
已采纳

如何在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?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • duanpo1821 2018-08-01 07:11
    最佳回答

    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');
    
    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题