我有2个多维数组,我想把它的值插入数据库表。
Array
(
[menu_categorie] => Array
(
[0] => Array
(
[name] => Breakfast
)
[1] => Array
(
[name] => Desert
)
)
[menu_meal_name] => Array
(
[0] => Array
(
[name] => Array
(
[0] => Salade
)
[price] => Array
(
[0] => 3
)
[description] => Array
(
[0] => Lorem
)
)
[1] => Array
(
[name] => Array
(
[0] => Chocolate
)
[price] => Array
(
[0] => 2
)
[description] => Array
(
[0] => Lorem
)
)
)
)
字符串
当前,$_POST 'menu_meal_name']中的值未被保存,并且仅存储$menu_categorie的最新值,忽略多个条目。如何增强代码以解决这些问题?
$menu_categorie = isset($_POST['menu_categorie']) ? map_deep( $_POST['menu_categorie'], 'sanitize_text_field' ) : array();
$menu_meal_name = isset($_POST['menu_meal_name']) ? map_deep( $_POST['menu_meal_name'], 'sanitize_text_field' ) : array();
global $wpdb;
$table_name = $wpdb->prefix . "restaurant";
// Start loop
if (!empty($menu_categorie) || !empty($menu_meal_name)) {
foreach ($menu_categorie as $key => $categorie_data) {
$categorie_name = isset($categorie_data['name']) ? $categorie_data['name'] : '';
if ($categorie_name) {
$meals = isset($menu_meal_name[$key]) ? $menu_meal_name[$key] : array();
foreach ($meals as $meal) {
$meal_name = isset($meal['name']) ? $meal['name'] : '';
$price = isset($meal['price']) ? floatval(str_replace(',', '.', $meal['price'])) : 0;
$description = isset($meal['description']) ? $meal['description'] : '';
if (!empty($categorie_name) || !empty($meal_name)) {
$current_time = current_time('mysql');
$data_to_insert = array(
'post_id' => $post_id,
'post_title' => get_the_title($post_id),
'categorie' => $categorie_name,
'meal_name' => $meal_name,
'price' => $price,
'pp' => 0,
'description' => $description,
);
$existing = $wpdb->get_row(
$wpdb->prepare(
"SELECT id FROM {$table_name} WHERE post_id = %d AND meal_name = %s",
absint($post_id),
$meal_name
)
);
if ($existing) {
$data_to_insert['aangepast_op'] = $current_time;
$wpdb->update(
$table_name,
$data_to_insert,
array('id' => $existing->id)
);
} else {
$data_to_insert['aangemaakt_op'] = $current_time;
$wpdb->insert($table_name, $data_to_insert);
}
}
}
}
}
}
型
1条答案
按热度按时间ut6juiuv1#
字符串
你能试试这样吗?
对不起谷歌翻译:)