【问题标题】:Get an array column based on the values of another column in PHP [duplicate]根据PHP中另一列的值获取数组列[重复]
【发布时间】:2019-04-28 23:02:08
【问题描述】:

我有一个多列 PHP 数组

Array (
    Array ('col1', 'col2', 'col3'),
);

如果col1 大于特定值,我如何获得col2 的数组?

我可以通过 foreach 循环来做到这一点,但我认为应该可以使用像 array_filter 这样的本机函数。

【问题讨论】:

    标签: php arrays array-filter


    【解决方案1】:

    简单地说,你最好使用 foreach 循环,因为你不必对数组进行多次迭代。您想要过滤和修改数组,这需要同时使用 array_filter()array_map() 才能获得您想要的:

    <?php
    
    $arr = [
        [5, 'col2-1', 'col3'],
        [10, 'col2-2', 'col3']
    ];
    
    $res = array_filter($arr, function($item) {
        return $item[0] > 7;
    });
    
    $res = array_map(function($item) {
        return $item[1];
    }, $res);
    
    var_dump($res);
    

    在这里测试:https://3v4l.org/HRTOJ

    【讨论】:

      猜你喜欢
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      相关资源
      最近更新 更多