douliedai4838 2013-09-11 11:28
浏览 131
已采纳

使用PHP中的整数过滤数组值

I am trying to filter a php array by comparing a field containing a unix date string ("start-unix-date") with the current unix time (simplified in this example as "15"). I want to keep only items where the unix date is in the future (>= than present).

Here is a simplified version of my code - based on this filtering method:

$my_array = array(
    array( 'start-date-unix' => '20' ), 
    array( 'start-date-unix'  => '10')
);

$unix_now = 15;

function filter_future($var) {
    return (is_array($var) && $var['start-date-unix'] >= $unix_now)
}

$filtered_array = array_filter($my_array, "filter_future");

var_dump($filtered_array);

The expected result:

The $filtered_array should keep only the item with a "start-date-unix" value of 20.

Actual result:

That filter doesn't do anything, every value is accepted. The $filtered_array still contains both items.

What works:

In the filter_future, if I enter the number (15) instead of the $unix_now variable, it works as expected: only the "20" item is kept.

So I suspect that there's an issue with $unix_now being a string vs an integer. I tried many methods of enforcing it being an integer but nothing seems to work :(

  • 写回答

5条回答 默认 最新

  • douzhuiqiu4923 2013-09-11 11:32
    关注

    $unix_now should be a global variable inside filter_future-function.

    $unix_now = 15;
    
    function filter_future($var) {
        global $unix_now;
        return (is_array($var) && (int) $var['start-date-unix'] >= $unix_now)
    }
    
    $filtered_array = array_filter($my_array, "filter_future");
    
    var_dump($filtered_array);
    

    The result:

    array(1) { [0]=> array(1) { ["start-date-unix"]=> string(2) "20" } } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。