PHP:我的foreach有什么问题?

时间:2018-03-10 20:16:42

标签: php loops if-statement foreach conditional

我的foreach不断回应我的if陈述的第一个条件,这对我没有任何意义。

如果您查看第一个代码段中的foreach,您会看到if检查是否$field === id || image_id。即使没有一个名为foreachIm and ID: $field => $type <br>的索引,id的每次迭代都会吐出image_id条件。是什么给了什么?

这是整个方法

  protected function create_db_table(string $table, array $fields) {
    global $wpdb;
    $table_name = $wpdb->prefix."$table";
    $table_charset = $wpdb->get_charset_collate();
    $field_names = [];
    $check_id = array_key_exists('id', $fields)  ? 'id' : 'image_id';

    foreach ($fields as $field => $type) {
      if ($field === 'id' || 'image_id') {
        echo "Im an ID: $field => $type <br>";
        $field_names[] = "$field $type UNSIGNED NOT NULL AUTO_INCREMENT";
      } else {
          echo "Im NOT and ID: $field => $type <br>";
          $field_names[] = "$field $type";
      }
    }

    $field_names = join(",\n", $field_names);

    // echo "<h1>$field_names</h1>";

    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            $field_names,
            PRIMARY KEY  ($check_id)
            ) $table_charset;";

    require_once ABSPATH.'wp-admin/includes/upgrade.php';

    dbDelta($sql);
  }

这就是我的称呼方式

function activation_methods() {
  $slider_settings = new SliderSettings;
  $slider_settings_fields = [
    'id'                => 'int(9)',
    'transition_time'   => 'int(9)',
    'loop_carousel'     => 'tinytext',
    'stop_on_hover'     => 'tinytext',
    'reverse_order'     => 'tinytext',
    'navigation_arrows' => 'tinytext',
    'show_pagination'   => 'tinytext'
  ];

  $slider_images = new SliderImages;
  $slider_images_fields = [
    'image_id'    => 'int(9)',
    'carousel_id' => 'int(9)',
    'image_url'   => 'text'
  ];

  $slider_settings->create_db('bb_slidersettings', $slider_settings_fields);
  $slider_images->create_db('bb_sliderimages', $slider_images_fields);
}
activation_methods();

2 个答案:

答案 0 :(得分:4)

$field === 'id' || 'image_id'应该是:

$field === 'id' || $field === 'image_id'

甚至更短:in_array($field, ['id', 'image_id'])

$field === 'id' || 'image_id' 始终评估为 TRUE ,与写作相同:

($field === 'id') || true

答案 1 :(得分:1)

使用$field === 'id' || 'image_id'时。 这里有两句话:

  1. $field等于'id'
  2. 'image_id'
  3. 正确的是:

    if($field === 'id' || $field === 'image_id')