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

如何在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条)

报告相同问题?

悬赏问题

  • ¥15 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低