How can I create an array from the values of another array's key?

前端 未结 4 756
走了就别回头了
走了就别回头了 2021-02-01 18:38

I have an array as follows:

$arr1 = array(
  0 => array(
    \'name\' => \'tom\',
    \'age\' => 22
  ),
  1 => array(
    \'name\' => \'nick\',
           


        
相关标签:
4条回答
  • 2021-02-01 19:24

    if you are using Laravel, then simply use array_pluck:

    $arr2 = array_pluck($arr1 , 'name');
    
    0 讨论(0)
  • 2021-02-01 19:33
    $array = array(0 => array('name' => 'tom', 'age' => 22), 1 => array('name' => 'nick', 'age' => 18));
    foreach($array as $arr => $a){
        $names[] = $array[$arr]["name"];
    }
    
    print_r($names); //Array ( [0] => tom [1] => nick ) 
    
    0 讨论(0)
  • 2021-02-01 19:36

    This can be done in still more simple way by using array_column

    $arr2= array_column($arr1, 'name');
    
    print_r($arr2); //Array ( [0] => tom [1] => nick )
    

    array_column is used to get the columns of a sub-array.

    0 讨论(0)
  • 2021-02-01 19:37

    Newer versions of PHP allow using array_map() with a function expression instead of a function name:

    $arr2 = array_map(function($person) {
        return $person['name'];
    }, $arr1);
    

    But if you are using a PHP < 5.3, it is much easier to use a simple loop, since array_map() would require to define a (probably global) function for this simple operation.

    $arr2 = array();
    
    foreach ($arr1 as $person) {
        $arr2[] = $person['name'];
    }
    
    // $arr2 now contains all names
    
    0 讨论(0)
提交回复
热议问题