可以使用PHP的array_combine创建一个带(稀疏)数字键的关联数组吗?

时间:2012-05-15 01:26:33

标签: php arrays

我使用preg_match在网页中查找键和值。一些键是数字,如101357,但大多数是字符串。当我使用array_combine创建一个包含这些键和值的数组时,它会将数字键转换为从键0开始的有序数组元素:

实测值:

"ABC"    => "Value1",
"101397" => "Value2",
"DEF"    => "Value3",
"401995" => "Value4"

所以$ keys = array(“ABC”,“101397”,“DEF”,“401995”)和$ vals = array(“Value1”,...)

print_r(array_combine($keys, $vals)) produces:

"ABC" => "Value1"
0     => "Value2"
"DEF" => "Value3"
1     => "Value4"

所以我丢失了键的值。在找到更优雅的解决方案(如果可能)之前,我将把array_combine放到

foreach($keys as $idx=>$key) 
{
    $result[$key] = $vals[$val];
}

1 个答案:

答案 0 :(得分:3)

我得到的结果与你不一样:

$array = array("ABC" => "Value1",
"101397" => "Value2",
"DEF" => "Value3",
"401995" => "Value4");

$keys = array_keys($array);
$values = array_values($array);

print_r(array_combine($keys, $values));

给出:

Array ( [ABC] => Value1 [101397] => Value2 [DEF] => Value3 [401995] => Value4 )

显示$keys$values的值:

print_r($keys);
print_r($values);

Array ( [0] => ABC [1] => 101397 [2] => DEF [3] => 401995 )
Array ( [0] => Value1 [1] => Value2 [2] => Value3 [3] => Value4 )

即使使用非字符串键也可以得到相同的结果。

$array = array("ABC" => "Value1",
101397 => "Value2",
"DEF"  => "Value3",
401995 => "Value4");

$keys = array_keys($array);
$values = array_values($array);

print_r(array_combine($keys, $values));

Array ( [ABC] => Value1 [101397] => Value2 [DEF] => Value3 [401995] => Value4 )