dongyongan9941 2014-02-18 14:33
浏览 7
已采纳

PHP - 按键检索子数组值

Given the following structure:

Array
(
    [0] => Array
        (
            [id_field] => 100
        )

    [1] => Array
        (
            [id_field] => 200
        )

    [2] => Array
        (
            [id_field] => 382
        )

    [3] => Array
        (
            [id_field] => 509
        )

    [4] => Array
        (
            [id_field] => 636
        )

    [5] => Array
        (
            [id_field] => 763
        )

    [6] => Array
        (
            [id_field] => 890
        )

    [7] => Array
        (
            [id_field] => 1017
        )

)

Is there a built in array method which can grab all id_field values?

I can loop over them for sure, but think maybe there is a built in that i cannot see in the manual that already does this?

  • 写回答

3条回答 默认 最新

  • dongzhong3688 2014-02-18 14:37
    关注

    If you have PHP 5.5.0+, you could use array_column():

    $result = array_column($data, 'id_field');
    

    If you're running an older PHP version, you can use the userland implentation of this function (written by the same author who wrote the original array_column() function).

    However, for simple use-cases, this can be implemented as function using a simple foreach loop. This isn't guaranteed to handle all possible cases, but it should be enough for the most part.

    function array_column2(array $arr, $column) {
        $result = array();
        foreach ($arr as $key => $value) {
            $result[] = $arr[$column];
        }
        return $result;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失