如何强制数组键's值为整数而不是字符串,当他们是数字


How to force array key's values to be integer instead of string when they are numeric?

我怎么能强迫所有数值是整数而不是字符串当一些PHP函数发生例如与array_replace() ?下面是一个例子:

我的$item是一个默认值的数组,var_dump($item)产生如下:

array (size=12)
  'id' => string '' (length=0)
  'cid' => int 2
  'pid' => string '' (length=0)
  'rid' => string '' (length=0)
  'section' => int 0
  'title' => string '' (length=0)
  'slug' => string '' (length=0)
  'image' => string '' (length=0)
  'description' => string '' (length=0)
  'ordering' => string '' (length=0)
  'created' => string '' (length=0)
  'modified' => string '' (length=0)

然后,我调用一个函数来更新$item数组与新值来自db与函数array_replace($item, $item_db);,当我再次var_dump($item),我得到这个:

array (size=12)
  'id' => string '12' (length=2)
  'cid' => string '1' (length=1)
  'pid' => string '0' (length=1)
  'rid' => string '37' (length=2)
  'section' => string '0' (length=1)
  'title' => string 'Article2' (length=8)
  'slug' => string 'articles123' (length=11)
  'image' => string 'e9213e52d235bd892b3337fce3172bed.jpg' (length=36)
  'description' => string '' (length=0)
  'ordering' => string '3' (length=1)
  'created' => string '2014-05-15 14:51:10' (length=19)
  'modified' => string '2014-05-15 23:29:40' (length=19)

我想要所有的数值(id, cid, pid, rid, section, ordering)的整数,除了createdmodified键。

如果不手动编写,我该如何做到这一点:

$item['section'] = (int) $item['section'];

您可以使用这样简单的foreach循环:

foreach ($array as $k => $v) {
   if ($k != 'created' && $k != 'modified') {
       $array[$k] = (int) $v;
   }
}

当然,如果您确定所有值都是数字,那么可以将它们转换为int。否则你必须使用:

foreach ($item as $k => $v) {
    if (is_numeric($v)) {
        $item[$k] = (int) $v;
    }
}

创建一个数组,其中包含您不希望重命名的值。然后循环遍历数组—在每次迭代中,检查当前键是否在$defaults数组中。如果不是,则将其压入一个新的数组($results),并将当前的数字偏移量作为键。如果不是,用当前键将其推入新的数组:

类似以下语句的内容:

$defaults = ['created', 'modified']; // Keys to be left untouched
$result = [];                        // Results array
$i = 0;                              // Numeric offset
foreach ($array as $key => $value) {
    if (!in_array($key, $defaults)) {
        $result[++$i] = $value;
    } else {
        $result[$key] = $value;
    }
}
print_r($result);