美文网首页
PHP操作数组学习

PHP操作数组学习

作者: 乖乖的鱼儿记 | 来源:发表于2016-03-14 15:24 被阅读0次

    开发中遇到一个数组操作的棘手问题好在一番搜索之后再网上找到了一些答案。
    说明一下这段文字引用于http://www.phpfensi.com/php/20140107/1147.html
    过滤关联数组的结果
    假定你得到了如下一个数组,但是你仅仅想操作价格低于$11.99的元素:

    Array 
    ( 
      [0] => Array 
        ( 
          [name] => checkers 
          [price] => 9.99 
        ) 
      [1] => Array 
        ( 
          [name] => chess 
          [price] => 12.99 
        ) 
      [2] => Array 
        ( 
          [name] => backgammon 
          [price] => 29.99 
        ) 
    ) ```
    
    使用array_reduce()函数可以很简单的实现,代码如下:
    ```php
    function filterGames($game){ 
     return ($game['price'] < 11.99); 
    } 
    $names = array_filter($games, 'filterGames'); 
    

    array_reduce()函数会过滤掉不满足回调函数的所有的元素,本例子的回调函数就是filterGames,任何价格低于11.99的元素会被留下,其他的会被剔除,该代码段的执行结果:

    Array 
    ( 
      [1] => Array 
        ( 
          [name] => checkers 
          [price] => 9.99 
        ) 
    ) 
    

    相关文章

      网友评论

          本文标题:PHP操作数组学习

          本文链接:https://www.haomeiwen.com/subject/jpuflttx.html