如何仅在值不存在的情况下翻转数组


How to flip array only if value not exists?

例如,我有一个类似的数组

$keys = array(
             'host', 
             'port' => 3306, 
             'database', 
             'username', 
             'password'
             );

PHP中,它看起来像这个

array(5) {
  [0]=>
  string(4) "host"
  ["port"]=>
  int(3306)
  [1]=>
  string(8) "database"
  [2]=>
  string(8) "username"
  [3]=>
  string(8) "password"
}

什么是最好的方式来翻转它,它会像这个

array(
     'host' => NULL, 
     'port' => 3306, 
     'database' => NULL, 
     'username' => NULL, 
     'password' => NULL
     )

基本上,我只需要翻转那些没有值的元素(在这种情况下,只有端口有值)。

可能在下面,代码将按照您在问题中提到的进行操作。但这不是一个翻转。

$keys = array(
         'host', 
         'port' => 3306, 
         'database', 
         'username', 
         'password'
         );
foreach ($keys as $key => $val) {
  if (is_int($key)) {
     $keys[$val] = NULL;
     unset($keys[$key]);
  }
}
var_dump($keys);

它执行以下步骤

  1. 在数组上循环
  2. 如果是3和4,则检查是否为数字键
  3. 在数组中创建一个新索引,其中数字键中的val指向NULL
  4. 最后从数组中取消设置旧的数字索引

我想为您发布一个替代方案,因为我认为您正遭受XY问题的困扰

<?php
$defaults= array(
     'host' => null
     'port' => 3306, 
     'database' => null, 
     'username' => null, 
     'password' => null
     );
$customizations = array(
     'host'=> 'localhost'
);
$params = array_merge($defaults, $customizations);
/* $params is now this:
   array(
     'host' => 'localhost'
     'port' => 3306, 
     'database' => null, 
     'username' => null, 
     'password' => null
     );
*/

试试这个:

$keys = array(
    'host', 
    'port' => 3306, 
    'database', 
    'username', 
    'password'
);
$counter = 0;
$a = [];
foreach ($keys as $key => $value) {
    if($key == $counter) {
        $a[$value] = NULL;
        $counter++;
    }
    else
    {
        $a[$key] = $value;
    }
}
print_r($a);