gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:36:02 25 4
gpt4 key购买 nike

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

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

和 Controller 为:

设置 Controller .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');

关于php - 如何在php中将对象数组转换为键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51627309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com