在我的公共函数中,我创建了一个具有两个值类型和id:
的数组public function easypost_database()
{
\EasyPost\EasyPost::setApiKey('mykey');
$cas = \EasyPost\CarrierAccount::all();
foreach ($cas as $key => $value) {
$this->services[] = array('type' => $value['type'],
'id' => $value['id']
);
}
}
我的数组看起来像这样:
Array
(
[0] => Array
(
[type] => CanadaPostAccount
[id] => myidcp0
)
[1] => Array
(
[type] => PurolatorAccount
[id] => myidp0
)
)
现在在我的另一个函数中,我想提取这些值并回显它们(实际上我想在下拉列表中插入这些值,但为了这个问题,让我们假设我会回应它们)。
所以我的其他功能如下:
public function settings_form($current)
{
$database = $this->easypost_database();
$services_a = $this->services;
foreach ($services_a as $key => $value) {
foreach ($value['type'] as $key => $val) {
print_r($val)
}
}
}
由于某种原因,我无法打印我的数组,因为数组返回一个空值(或只是数组的第一个值)。
我可以创建一个数组并在foreach循环外推送我的值,但我正在寻找一种更优雅的方式来处理我的代码。
更新:
我总是可以这样做:
$services_a = $this->services;
$service_type = array();
foreach ($services_a as $key => $value) {
array_push($service_type, $value['type']);
}
foreach ($service_type as $val) {
$s .= $this->formDropdown('service[]', $val, $this->settings['service']) . ' ' . $val . '<br>';
}
但我正在寻找更短的路。
答案 0 :(得分:2)
试试这个:
public function settings_form($current)
{
$database = $this->easypost_database();
$services_a = $this->services;
foreach ($services_a as $key => $value) {
foreach ($value as $key => $val) {
if( $key == 'type' ){
print_r($val);
}
}
}
}