doutang6130 2015-12-13 21:59
浏览 10
已采纳

如何仅使用数字键提取数组值?

Considering array like:

$arr = array(
  'key' => 'foo'
  'key2' => 'bar',
   0 => 'num_foo',
   1 => 'num_bar'

);

How to extract values under 0 & 1? (Besides using for loop). Maybe any standard function do the job?

  • 写回答

3条回答 默认 最新

  • duanjiu1003 2015-12-13 22:07
    关注

    If you’re using a PHP version >= 5.6, you can use array_filter, with the flag that tells it to pass the key to the callback function.

    $arr = array(
      'key' => 'foo',
      'key2' => 'bar',
       0 => 'num_foo',
       1 => 'num_bar'
    );
    
    $new_array = array_filter($arr, function($key) {
      return is_numeric($key);
    }, ARRAY_FILTER_USE_KEY);
    
    var_dump($new_array);
    

    https://3v4l.org/qfar9


    Edit: As Robbie pointed out, using is_numeric is the better choice here. (Previously my example used is_int.)


    Edit 2: Perhaps is_int is actually the better choice here. is_numeric would return true for values such as +0123.45e6, or hexadecimal/binary number notations as well – not sure if that’s desired.

    is_int would normally return false for a value such as '1'. It works here, because we are dealing with arrays – and PHP automatically converts array keys to integer, if they are an “integer string.”

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 eclipse连接sap后代码跑出来空白
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi