如何将对象数组转换为 php 中的键值对

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

我有一个对象数组,我需要转换成键值对,我的代码是

我有一个模型: 型号 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'],
              ]
}

控制器为:

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;
}

我收到以下错误:

ErrorException (E_NOTICE) Trying to get property 'code' of non-object

我哪里做错了,我该如何纠正?

由于您尝试迭代的数据是一个数组(来自对象),因此符号应该是...

$result[$currency['code']] = $currency['name'];

或者如果您想要更短的版本(取决于 PHP 的版本),请使用 array_column()...

$result = array_column($currency_list, 'name', 'code');
foreach ($currency_info as $currency) {
    $result[$currency['code']] = $currency['name'];
}

currency_info函数return数组,所以把它当作数组。您正在使用 $currency->code 从数组访问 code 键,请改用 $currency["code"]

public function index() {
    $setting = new Setting();
    $currency_list = $setting->currency_info();

    $result = [];
    foreach ($currency_list as $currency) {
        $result[$currency["code"]] = $currency["name"];
    }
    return $result;
}