【问题标题】:PHP array - Foreach, dynamic value - StrangePHP数组 - Foreach,动态值 - 奇怪
【发布时间】:2017-10-21 10:41:06
【问题描述】:

我尝试在 PHP 关联数组中生成动态值列表,但我做不到。

1) 使用此代码

foreach ($states as $state) {
  $state_options[$state->country()->name()][$state->ID()] = $state->name();
}

我得到

<optgroup label="France">
<option value="01 - Ain">01 - Ain</option>
<option value="02 - Aisne">02 - Aisne</option>
</optgroup>

我在值中获取名称而不是 ID。

2) 使用此代码

foreach ($states as $state) {
  $state_options[$state->country()->name()][$state->name()] = $state->ID();
}

我得到

<optgroup label="France">
<option value="01 - Ain">77</option>
<option value="02 - Aisne">78</option>
<option value="03 - Allier">79</option>
</optgroup>

我可以得到身份证。

我的目标是获得

<optgroup label="France">
<option value="77">01 - Ain</option>
<option value="78">02 - Aisne</option>
<option value="79">03 - Allier</option>
</optgroup>

非常感谢您的帮助

22/10/17 cmets 后编辑

我的完整代码

add_filter( 'gform_address_types', 'france_address_type' );
function france_address_type( $address_types ) {

$state_options = array('' => array('' => ''));
$states        = EEM_State::instance()->get_all_active_states();
if (! empty($states)) {
    foreach ($states as $state) {
        if ($state instanceof EE_State) {
            $state_options[$state->country()->name()][$state->ID()] = $state->name();
        }
    }
}

$address_types[ 'france' ] = array(
    'label'       => 'France',
    'country'     => 'France',
    'zip_label'   => 'Code Postal',
    'state_label' => 'Département',
    'states'      => $state_options
);

return $address_types;
}

【问题讨论】:

  • 现在显示生成select amd options的代码
  • 你试过颠倒$state_options[$state-&gt;country()-&gt;name()][$state-&gt;name()] = $state-&gt;ID()中的值和键,所以交换name()ID()
  • @u_mulder 我已经写了完整的代码。
  • @NigelRen 你建议“$state_options[$state->country()->name()][$state->name()] = $state->ID();” ?导致它在我的帖子中是我的解决方案 2。此代码正在运行。

标签: php arrays foreach associative-array


【解决方案1】:

由于$state-&gt;name()显然对应于“01-Ain”,而$state-&gt;ID()对应于77,所以使用后者作为键,前者作为值:

foreach ($states as $state) {
  $state_options[$state->country()->name()][$state->ID()] = $state->name();
}

【讨论】:

  • 这是我在“1) 使用此代码”上尝试的,但我无法获得 ID()
  • @Jahnichen 这很奇怪。 $state-&gt;ID()到底会返回ID吗?添加一些日志记录。
【解决方案2】:

你可以这样尝试,你可以得到预期的结果。

<optgroup label="France">
   <?php foreach ($states as $state) { ?>
       <option value="<?php echo $state->ID(); ?>">
       <?php echo $state->name();?></option>
   <?php } ?>
</optgroup>

【讨论】:

  • optgroup 标签显然 $state-&gt;country()-&gt;name()
  • 是的 optgroup 是在 foreach 中生成的。此外,我需要将代码包装在一个变量中。我刚刚发布了完整的代码。
猜你喜欢
  • 2019-08-11
  • 1970-01-01
  • 2014-01-15
  • 2013-04-26
  • 2019-03-02
  • 2016-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多