如何合并两个数组

时间:2019-01-19 19:59:18

标签: php arrays

我有一个表格,我用它来更新用户个人资料。问题是我不想强制所有字段,因此如果用户留下空白字段,那么已经存储在数据库中的值将更新为空白或空值。因此,我决定查询数据库并获取一个已存储的值数组,然后从用户表单中获取一个值数组。我需要以一种方式合并两个数组,以便在表单中插入新值时可以更新数据库字段,而在表单字段为空时保留旧数据库值。

我知道我可以使用数组执行以下withut的操作,但是在这种情况下我不知道如何使用预处理语句

if(!empty($user_last))
  $update_values[] = "user_last='".$user_last."'";
$update_values_imploded = implode(', ', $update_values);

if( !empty($update_values) ){
 $q = "UPDATE users SET $update_values_imploded WHERE user_id='$userid' ";
 $r = mysqli_query($conn,$q);

 if($r){
$_SESSION['success_msg'] = 'profile updated!';
header("location: ../client_profile.php");
exit();
}
}

我尝试过的数组方法如下,但是它实际上不能正常工作。

$merged_array =  array_unique(array_merge($database_rows, $form_data));

您还有其他想法吗?非常感谢

这是模拟了from数组的完整代码

$km_user_id= 2;

// this array comes from the form
$from_array = array(
    'km_user_first_name' => 'Antonio', 
    'km_user_last_name' => 'Acri',
    'km_user_address' => 'via pola',
    'km_user_city' => 'roma',
    'km_user_city_prov' => '',
    'km_user_postcode' => '',
    'km_user_email' => '',
    'km_user_website' => 'url',
    'km_user_telephone' =>  '123456',
    'km_user_mobile' => '',
    'km_user_fiscalcode' => '',
    'km_user_document' => '',
    'km_user_document_number' => '',
    'km_user_document_exp' =>  '',
    'km_user_birth_place' => '',
    'km_user_birth_date' => ''


);


   // select vakues from database

   $query= "SELECT km_user_first_name, km_user_last_name, km_user_address, km_user_city, km_user_city_prov, km_user_postcode, km_user_email, km_user_website, km_user_telephone, km_user_mobile, km_user_fiscalcode, km_user_document, km_user_document_number, km_user_document_exp, km_user_birth_place, km_user_birth_date FROM km_users WHERE km_user_id= ?";
   $stmt = mysqli_prepare($db_user_conn, $query);
   mysqli_stmt_bind_param($stmt, 'i', $km_user_id);
   mysqli_stmt_execute($stmt);
   $result = mysqli_stmt_get_result($stmt);

   $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
   print_r($row);


?>
<br>
<br>
<?php

print_r($from_array);


?>
<br>
<br>
<?php

$result =  array_merge($from_array, $row); 
print_r($result);

您可以在合并数组中看到应该为[km_user_address] => via roma 11的值[km_user_address] => via pola

4 个答案:

答案 0 :(得分:1)

希望我能解决您的问题(如果没有,请发表评论)。

如果要将表单数组作为主要值,并且仅当其为空时才使用第二个数组中的值,则可以在array_filterarray_merge上使用组合。

考虑以下示例:

$form = array("km_user_first_name" => "Alice", "km_user_address" => "");
$row = array("km_user_first_name" => "Boby", "km_user_address" => "via pola");
$res = array_merge($row, array_filter($form));

这将输出:

Array
(
    [km_user_first_name] => Alice
    [km_user_address] => via pola
)

我知道我使用PHP documentation中所说的form数组(感谢@Nick):

  

如果输入数组具有相同的字符串键,则后一个值   该键将覆盖前一个键

希望有帮助!

答案 1 :(得分:1)

您应该依靠准备好的陈述。

仅使用白名单作为动态SQL构建列名。过滤出空字符串''。插入匿名的准备好的语句参数?并生成类型说明符字符串。然后将值作为绑定参数传递。

这应该可以工作(无法测试)。

<?php
declare (strict_types=1);

$km_user_id = 2;

// this array comes from the form
$form_array =
[
  'km_user_first_name'      => 'Antonio',
  'km_user_last_name'       => 'Acri',
  'km_user_address'         => 'via pola',
  'km_user_city'            => 'roma',
  'km_user_city_prov'       => '',
  'km_user_postcode'        => '',
  'km_user_email'           => '',
  'km_user_website'         => 'url',
  'km_user_telephone'       => '123456',
  'km_user_mobile'          => '',
  'km_user_fiscalcode'      => '',
  'km_user_document'        => '',
  'km_user_document_number' => '',
  'km_user_document_exp'    => '',
  'km_user_birth_place'     => '',
  'km_user_birth_date'      => '',
];

$white_list =
[
  'DEBUGkm_user_first_name'      => true, // DEBUG TEST filter
  'km_user_last_name'       => true,
  'km_user_address'         => true,
  'km_user_city'            => true,
  'km_user_city_prov'       => true,
  'km_user_postcode'        => true,
  'km_user_email'           => true,
  'km_user_website'         => true,
  'km_user_telephone'       => true,
  'km_user_mobile'          => true,
  'km_user_fiscalcode'      => true,
  'km_user_document'        => true,
  'km_user_document_number' => true,
  'km_user_document_exp'    => true,
  'km_user_birth_place'     => true,
  'km_user_birth_date'      => true,
];


// filter by whitelist and remove  ''  but NOT  '0'
$non_empty = array_intersect_key(array_filter($form_array, function($v){return $v !== '';}), $white_list);

if(!empty($non_empty))
{
  $cols   = '`' . implode('` = ?, `', array_keys($non_empty)) . ' = ?';
  $query  = "UPDATE `users` SET $cols WHERE `user_id` = ?";
  $values = array_values($non_empty);
  array_push($values, $km_user_id);

  $stmt = mysqli_prepare($db_user_conn, $query);
  mysqli_stmt_bind_param($stmt, str_repeat('s', count($non_empty)).'i', ...$values);
  mysqli_stmt_execute($stmt);
  // TODO: error handling
}

km_user_first_name不应更新,因为它不在白名单中。经过测试后,请删除前缀DEBUG

答案 2 :(得分:1)

我想用完全不同的方法提供第二个答案。

可能最好,最安全的方法是执行一个简单的静态预准备语句,并使空参数的处理达到SQL:

$sql_update = <<<_SQL_

  UPDATE 
    `users`
  SET
    `km_user_first_name`      = COALESCE(NULLIF(?, ''), `km_user_first_name`      ),
    `km_user_last_name`       = COALESCE(NULLIF(?, ''), `km_user_last_name`       ),
    `km_user_address`         = COALESCE(NULLIF(?, ''), `km_user_address`         ),
    `km_user_city`            = COALESCE(NULLIF(?, ''), `km_user_city`            ),
    `km_user_city_prov`       = COALESCE(NULLIF(?, ''), `km_user_city_prov`       ),
    `km_user_postcode`        = COALESCE(NULLIF(?, ''), `km_user_postcode`        ),
    `km_user_email`           = COALESCE(NULLIF(?, ''), `km_user_email`           ),
    `km_user_website`         = COALESCE(NULLIF(?, ''), `km_user_website`         ),
    `km_user_telephone`       = COALESCE(NULLIF(?, ''), `km_user_telephone`       ),
    `km_user_mobile`          = COALESCE(NULLIF(?, ''), `km_user_mobile`          ),
    `km_user_fiscalcode`      = COALESCE(NULLIF(?, ''), `km_user_fiscalcode`      ),
    `km_user_document`        = COALESCE(NULLIF(?, ''), `km_user_document`        ),
    `km_user_document_number` = COALESCE(NULLIF(?, ''), `km_user_document_number` ),
    `km_user_document_exp`    = COALESCE(NULLIF(?, ''), `km_user_document_exp`    ),
    `km_user_birth_place`     = COALESCE(NULLIF(?, ''), `km_user_birth_place`     ),
    `km_user_birth_date`      = COALESCE(NULLIF(?, ''), `km_user_birth_date`      )
  WHERE
    `user_id` = ?
  ;

_SQL_;

$stmt = $db_user_conn->prepare($sql_update);

mysqli_stmt_bind_param
(
  $stmt,  'ssssssssssssssssi',

  $form_data['km_user_first_name'],
  $form_data['km_user_last_name'],
  $form_data['km_user_address'],
  $form_data['km_user_city'],
  $form_data['km_user_city_prov'],
  $form_data['km_user_postcode'],
  $form_data['km_user_email'],
  $form_data['km_user_website'],
  $form_data['km_user_telephone'],
  $form_data['km_user_mobile'],
  $form_data['km_user_fiscalcode'],
  $form_data['km_user_document'],
  $form_data['km_user_document_number'],
  $form_data['km_user_document_exp'],
  $form_data['km_user_birth_place'],
  $form_data['km_user_birth_date'],
  $km_user_id
);

mysqli_stmt_execute($stmt);

答案 3 :(得分:0)

为什么要创建另一个数组?您可以真正编辑已经拥有的阵列。   例如 : 您从数据库中获取索引数组 用值填充表格,以便用户可以看到旧信息。用户进行编辑时,说出他的名字myArray ['name'] = $_POST ['name']