我的foreach
不断回应我的if
陈述的第一个条件,这对我没有任何意义。
如果您查看第一个代码段中的foreach
,您会看到if
检查是否$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();
答案 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'
时。
这里有两句话:
$field
等于'id'
'image_id'
正确的是:
if($field === 'id' || $field === 'image_id')