doumei8126 2018-04-30 13:30
浏览 10
已采纳

从数组PHP中删除负整数[重复]

This question already has an answer here:

I'm trying to remove all negative integers from the following array :

$array = array([-122,121,-124,124,-121,122,-122,124,-121,124,-122,125,-121,121,-123,122,-124,120]);

I've tried the following, it's not working as I don't really understand how array_filter works :

function positive($var) {
  if ($var >= 0) {
    return $var;
  }
}

print_r(array_filter($array, positive($var)));

How would I send each value to the positive function? Or is there a better way of doing this? array_walk or array_map maybe?

</div>
  • 写回答

2条回答 默认 最新

  • dqxboe2628 2018-04-30 13:38
    关注

    Use this code:

    <?php
    $array = array([-122,121,-124,124,-121,122,-122,124,-121,124,-122,125,-121,121,-123,122,-124,120]);
    
    function positive($var) 
    {
        if ($var >= 0) 
        {
            return true;
        }
    }
    
    print_r(array_filter($array[0], 'positive'));
    

    You had to pass $array[0] as parameter to modify array. You have declared array with array in first element array([-122,...,-124,120]); so to filter array you need to pass $array[0].

    Output is:

    Array ( [1] => 121 [3] => 124 [5] => 122 [7] => 124 [9] => 124 [11] => 125 [13] => 121 [15] => 122 [17] => 120 )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案