$result = array_merge($arr1,$arr2);
我想排除$arr2
的数值,是否有选项?
评论后编辑:
$arr1 = array('key' => 1);
$arr2 = array('test',1 => 'test', 'key2' => 2);
处理后我需要结果:
array('key' => 1,'key2' => 2);
排除数字键
答案 0 :(得分:1)
您似乎想要array_filter
$arr2
的密钥,首先:
function not_numeric( $object ) {
return !is_numeric( $object );
}
$no_numeric_keys = array_filter( array_keys( $arr2 ), not_numeric );
$no_numeric_array = array_intersect_keys( $arr2, $no_numeric_keys );
$result = array_merge( $arr1, $no_numeric_array );
答案 1 :(得分:1)
在使用$result = array_merge($arr1,$arr2);
:
foreach ($result as $key => $value) {
if (is_numeric($key)) {
unset($result[$key]);
}
}
修改强> 尽可能少的行(1) - 按照新标题的要求:
foreach ($result as $key => $value) { if (is_numeric($key)) { unset($result[$key]); } }
答案 2 :(得分:0)
只需遍历每个数组并测试密钥是否为字符串:
$output = array();
foreach($arr1 as $key => $value) {
if(is_string($key)) {
$output[$key] = $value;
}
}
foreach($arr2 as $key => $value) {
if(is_string($key)) {
$output[$key] = $value;
}
}
修改强> 既然你说优雅......
function merge_arrays_string_keys()
{
$output = array();
foreach(func_get_args() as $arr)
{
if(is_array($arr))
{
foreach($arr as $key => $value) {
if(is_string($key) {
$output[$key] = $value;
}
}
}
}
return $output;
}
答案 3 :(得分:0)
$test = array('test', 1 => 'test', 'key2' => 2, 33, 3 => 33, 'foo' => 'bar');
$test_non_num = array_intersect_key(
$test,
array_flip(
array_diff(
array_keys($test),
array_filter(array_keys($test), 'is_int'))));
print_r($test_non_num); // key2=>2, foo=>bar
答案 4 :(得分:0)
使用此代码,它也会执行要求。
<?php
$result = array ( 1,"pavunkumar","bks", 123 , "3" ) ;
array_walk($result,'test_print');
print_r ( $result ) ;
function test_print( $val , $key )
{
global $result;
if ( gettype ( $val ) == 'integer' )
{
unset ( $result[$key] ) ;
}
}
答案 5 :(得分:0)
array_diff_ukey($m=$arr2+$arr1,$m,function($k){return is_string($k);})