Php 将数组中键的数据类型从数字更改为字符串
我有两个带数字键的数组。这是一个小例子:Php 将数组中键的数据类型从数字更改为字符串,php,arrays,data-conversion,Php,Arrays,Data Conversion,我有两个带数字键的数组。这是一个小例子: $test_a = array(1 => 'one', 2 => '二'); $test_b = array(2 => 'two', 4 => 'four'); 我想将它们与array\u merge()合并,以接收$test\u c数组: $test_c = array( 1 => 'one', 2 => 'two', 4 => 'four' ); 该手册提到: 带有数字键的输入数组
$test_a = array(1 => 'one', 2 => '二');
$test_b = array(2 => 'two', 4 => 'four');
我想将它们与array\u merge()
合并,以接收$test\u c
数组:
$test_c = array(
1 => 'one',
2 => 'two',
4 => 'four'
);
该手册提到:
带有数字键的输入数组中的值将在结果数组中以从零开始递增的键重新编号
这似乎是真的,因为:
$test_c = array_merge($test_a, $test_b);
var_dump($test_c);
返回:
array (size=4)
0 => string 'one' (length=3)
1 => string '二' (length=3)
2 => string 'two' (length=3)
3 => string 'four' (length=4)
我尝试了什么:
foreach($test_a as $key => $value) $test_a[(string)($key)] = $value;
…键仍然是数字foreach($test_a as $key => $value) $test_a['' . $key . ''] = $value;
也不行。这些键仍然是数字键foreach($test_a as $key => $value) $test_a[' ' . $key . ' '] = $value;
当我添加trim()
时:
这些键被转换回数字
基本上,我想合并这两个数组。我想唯一的解决方案是找到一种将键从数字数据类型转换为字符串数据类型的方法。如果你能另外解释“自动转换”的事情,我会完全满意。你可以在两个数组上使用
+
操作符,如下所示:
$test_a = array(1 => 'one', 2 => '二');
$test_b = array(2 => 'two', 4 => 'four');
var_dump( $test_b + $test_a);
这:
它不是按照您要查找的确切顺序排列的,但是您可以使用它按键进行排序。您所谓的“自动转换”实际上称为类型强制,在PHP中称为 简单地说,我做到了:
foreach($new as $k => $v)
{
$old[$k] = $v;
}
// This will overwrite all values in OLD with any existing
// matching value in NEW
// And keep all non matching values from OLD intact.
// No reindexing, and complete overwrite
// Working with all kind of data
$test_a = array(1 => 'one', 2 => '二');
$test_b = array(2 => 'two', 4 => 'four');
var_dump( $test_b + $test_a);
array(3) {
[2]=>
string(3) "two"
[4]=>
string(4) "four"
[1]=>
string(3) "one"
}
foreach($new as $k => $v)
{
$old[$k] = $v;
}
// This will overwrite all values in OLD with any existing
// matching value in NEW
// And keep all non matching values from OLD intact.
// No reindexing, and complete overwrite
// Working with all kind of data