dqqyp90576 2016-01-25 18:34
浏览 17
已采纳

PHP函数从数组中获取所需的值

function transformArray($array, $key)
{
  $transformed = [];
  foreach ($array as $k => $value) {
   $transformed[] = $value[$key]
 }
 return $transformed;
}

$array = [
0 => [
'key' => 1,
'key2' => 2
]
];

transformArray($array, 'key2');

Often I need function to build array from multidimesions array, for that I'm write function like in example, some frameworks have own function to do this, maybe for this solution exist shortest way with standart PHP functions ?

  • 写回答

1条回答 默认 最新

  • duanjie2940 2016-01-25 18:45
    关注

    Take a look to array_column function (supported since PHP 5.5).
    It returns the values from a single column in the input multi-dimensional array.
    Example from official documentation:

    $records = array(
        array(
            'id' => 2135,
            'first_name' => 'John',
            'last_name' => 'Doe',
        ),
        array(
            'id' => 3245,
            'first_name' => 'Sally',
            'last_name' => 'Smith',
        ),
        array(
            'id' => 5342,
            'first_name' => 'Jane',
            'last_name' => 'Jones',
        ),
        array(
            'id' => 5623,
            'first_name' => 'Peter',
            'last_name' => 'Doe',
        )
    );
    
    $first_names = array_column($records, 'first_name');
    print_r($first_names);
    

    // output:
            Array
        (
            [0] => John
            [1] => Sally
            [2] => Jane
            [3] => Peter
        )
    

    http://php.net/manual/ru/function.array-column.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?