如何使用在foreach循环中定义的外部循环的php变量

时间:2018-03-14 15:02:39

标签: php wordpress foreach

我知道之前已经回答了这些问题,并且我应用了所有可能的解决方案。我在foreach循环之前定义了所有变量,但仍然没有工作。我的代码在这里:

$settings_table = $wpdb->prefix."wpsp_settings";
$sel_setting = $wpdb->get_results("select * from $settings_table");
$school_name = "";
$school_logo = "";
$school_add = "";
$school_city = "";
$school_state = "";
$school_country = "";
$school_number = "";
$school_email = "";
$school_site = "";
foreach( $sel_setting as $setting ) :
  ($setting->id == 1) ? $school_name = $setting->option_value : $school_name = "";
  ($setting->id == 2) ? $school_logo = $setting->option_value : $school_logo = "";
  ($setting->id == 6) ? $school_add = $setting->option_value : $school_add = "";
  ($setting->id == 7) ? $school_city = $setting->option_value : $school_city = "";
  ($setting->id == 8) ? $school_state = $setting->option_value : $school_state = "";
  ($setting->id == 9) ? $school_country = $setting->option_value : $school_country = "";
  ($setting->id == 10) ? $school_number = $setting->option_value : $school_number = "";
  ($setting->id == 12) ? $school_email = $setting->option_value : $school_email = "";
  ($setting->id == 13) ? $school_site = $setting->option_value : $school_site = "";
endforeach; ?>

2 个答案:

答案 0 :(得分:2)

每次围绕循环重置值,就像你说的每个项目一样......

  ($setting->id == 1) ? $school_name = $setting->option_value : $school_name = "";

由于此循环对$ setting-> id的值不同,因此会重置所有不匹配的值。

使用switch... case...结构会更好......

foreach( $sel_setting as $setting ) {
    switch ($setting->id)   {
        case (1):
            $school_name = $setting->option_value;
            break;
        case (2):
            $school_logo = $setting->option_value;
            break;
        // Same for all the others.
    }
}

答案 1 :(得分:1)

它没有感觉:

foreach( $sel_setting as $setting ) {
  switch ($setting->id) {
    case 1:
      $school_name = $setting->option_value;
      break;
    case 2:
      $school_logo = $setting->option_value;
      break;
    ...
    case 13:
      $school_site = $setting->option_value;
      break;
  }
}

例如,如果$ setting-> id == 5,则将所有变量设置为空字符串OR如果$ setting-> id == 1,则将$ school_name设置为option_value但同时设置所有其他变量空白字符串。

简单的解决方案是使用如下所示的switch / case语句:

closed='right'