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

时间:2018-08-01 07:08:59

标签: php arrays laravel object keyvaluepair

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

我的模型如下: 模型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)试图获取非对象的属性“代码”

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

3 个答案:

答案 0 :(得分:3)

由于您要遍历的数据是数组(来自对象),因此符号应为...

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

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

$result = array_column($currency_list, 'name', 'code');

答案 1 :(得分:2)

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

答案 2 :(得分:2)

currency_info函数返回数组,因此将其视为数组。您正在使用$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;
}