douxue7196 2013-11-11 08:55
浏览 58

如果变量是int值,array_combine php函数不保留字符串变量的数据类型

array_combine php function doesn't preserve data type of string variable if the variable is int value

A simple example :

$a = array('1', '2');
$b = array('first', 'second');
$c = array_combine($a, $b);
$ak = array_keys($c);
var_dump($ak);

This will produce output as : integer values of 1 and 2.

What i wanted is to preserve string type of values 1 and 2

for temporary, i have used :

array_walk to to eventually achieve what i want.

  • 写回答

1条回答 默认 最新

  • douzhao1912 2013-11-11 09:01
    关注

    This is not because specific behavior of array_combine() function, but because of valid-integer keys type-casting in PHP arrays:

    $array = [1=>'foo', '2'=>'bar', 'x'=>'baz'];
    var_dump($array); // 1 and 2 are int
    

    There are also some other rules with keys type-casting (see link above).

    However, there are some tricks to achieve string keys anyway, like:

    $obj = new StdClass();
    $obj->{'1'}='foo';
    var_dump((array)$obj);//array(1) { ["1"]=> string(3) "foo" } 
    

    -but that is only for information - I would not recommend to use that. For your question, you can use something like array_map() applying it to result of array_keys() - but that will not save you - you'll not be able to determine which key was integer and which was string.

    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型