【问题标题】:Show data type of all the elements in the array显示数组中所有元素的数据类型
【发布时间】:2016-02-12 18:07:10
【问题描述】:

我有一个数组

array:23 [▼
  "cpe_mac" => "204492519985"
  "bandwidth_max_up" => 30000
  "bandwidth_max_down" => 50000
  "filter_icmp_inbound" => true
  "dmz_enabled" => false
  "dmz_host" => "http:\/\/ddd.com"
  "vlan_id" => 2
  "dns" => array:2 [▶]
  "xdns_mode" => 0
  "cfprofileid" => 11111
  "stub_response" => 0
  "acl_mode" => 1
  "portal_url" => "http:\/\/portal.com"
  "fullbandwidth_max_up" => 1000000
  "fullbandwidth_max_down" => 2000000
  "fullbandwidth_guaranty_up" => 300000
  "fullbandwidth_guaranty_down" => 400000
  "account_id" => 1000
  "location_id" => 3333
  "network_count" => 3
  "group_name" => "test_group"
  "vse_id" => 20
  "firewall_enabled" => false
]

我想知道他们每个人的数据类型,所以我这样做了

$cpe_type = [];
foreach ($cpe as $k => $v) {
    $cpe_type[$k] = gettype($v);
}

我得到了我想要的

array:23 [▼
  "cpe_mac" => "string"
  "bandwidth_max_up" => "integer"
  "bandwidth_max_down" => "integer"
  "filter_icmp_inbound" => "boolean"
  "dmz_enabled" => "boolean"
  "dmz_host" => "string"
  "vlan_id" => "integer"
  "dns" => "array"
  "xdns_mode" => "integer"
  "cfprofileid" => "integer"
  "stub_response" => "integer"
  "acl_mode" => "integer"
  "portal_url" => "string"
  "fullbandwidth_max_up" => "integer"
  "fullbandwidth_max_down" => "integer"
  "fullbandwidth_guaranty_up" => "integer"
  "fullbandwidth_guaranty_down" => "integer"
  "account_id" => "integer"
  "location_id" => "integer"
  "network_count" => "integer"
  "group_name" => "string"
  "vse_id" => "integer"
  "firewall_enabled" => "boolean"
]

是否有任何预制的 PHP 函数可以为我提供类似的功能?

【问题讨论】:

标签: php arrays elements gettype iterated-function


【解决方案1】:

从调试的角度来看,var_dump 将向您展示 PHP 中任何对象的类型和值的可呈现输出。

从编码的角度来看,array_map 是转换数组的最佳选择。只需给它一个回调,它就会转换所有的值:

array_map('gettype', $array);

Here 是一个有效的 phpplayground 示例。

【讨论】:

    【解决方案2】:

    你可以使用array_map:

    var_dump(array_map('gettype', $array));
    

    【讨论】:

    • "是否有任何预制的 PHP 函数可以为我提供类似的功能?"这不是预制函数。
    • @FrankerZ 从什么时候开始 array_map 不是一个预制函数?
    • @hek2mgl,我认为 FrankerZ 的意思是里面的回调不是预制的,而是 IMO,最好的答案还在这里
    • array_map('gettype', $array) 还不够吗?
    【解决方案3】:

    以 gettype 作为回调的 ArrayMap 在您的情况下就足够了。

    这将是您想要实现的最接近的本机实现。

    【讨论】:

      猜你喜欢
      • 2013-04-19
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 2014-07-29
      • 2012-02-12
      • 2010-10-20
      • 1970-01-01
      相关资源
      最近更新 更多