代码之家  ›  专栏  ›  技术社区  ›  Brandon Benefield

PHP:我的foreach怎么了?

  •  1
  • Brandon Benefield  · 技术社区  · 6 年前

    我的 foreach 持续回声是我的第一个条件 if 这对我来说毫无意义。

    如果你看看 foreach公司 在第一段代码中,您将看到 如果 检查 $field === id || image_id 。的每个迭代 foreach公司 吐出 Im 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 回复  |  直到 6 年前
        1
  •  4
  •   Marco    6 年前

    $field === 'id' || 'image_id' 应为:

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

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


    $字段===“id”| |“image\u id” 总是 评估至 符合事实的 ,这与写作一样:

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

        2
  •  1
  •   Mateus Gabi    6 年前

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

    1. $field 等于 'id'
    2. 'image_id'

    正确的是:

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