如何在没有键和没有循环的情况下将数组键值转换为一个数组? [重复]

如何在没有键和没有循环的情况下将数组键值转换为一个数组?  [重复]

问题描述:

This question already has an answer here:

I have this array:

Array
(
    [0] => Array
        (
            [fName] => Alice
            [lName] => Gibson
        )

    [1] => Array
        (
            [fName] => Jack
            [lName] => Smith
        )

    [2] => Array
        (
            [fName] => Bruce
            [lName] => Lee
        )

)

How to get an array with all fName values for instance:

["Alice","Jack","Bruce"]

What I've tried and worked is:

foreach($myArray as $info){
       $newArray[] = $info['fName'];      
}

question:

is it possible to use a single function instead of looping?

</div>

此问题已经存在 这里有一个答案: p>

  • 获取多维数组中特定列的所有值 5 answers span> li> ul> div>

    我有这个数组: p>

      Array 
    (
     [0] =&gt;数组
    (
     [fName] =&gt; Alice 
     [lName] =&gt; Gibson 
    )\  n 
     [1] =&gt;数组
    (
     [fName] =&gt; Jack 
     [lName] =&gt; Smith 
    )
     
     [2] =&gt;数组
    (
      [fName] =&gt; Bruce 
     [lName] =&gt; Lee 
    )
     
    )
      code>  pre> 
     
     

    如何获取包含所有fName值的数组 F 或实例: p>

      [“Alice”,“Jack”,“Bruce”] 
      code>  pre> 
     
     

    我是什么 尝试和工作的是: p>

      foreach($ myArray as $ info){
     $ newArray [] = $ info ['fName'];  
    } 
      code>  pre> 
     
     

    问题: strong> p>

    是否可以使用单个函数代替 循环? p> div>

You can use array_column

array_column($array, 'fName');

array_column returns all the values in a single column with the specified key.

Use array_column.

$fname = array_column($arr, "fName");

https://3v4l.org/OIGNM

An alternative is to use array_map() which applies the callback to each element in the array, as follows:

$arr = [["fName" => "Alice", "lName" => "Gibson"],
        ["fName" => "Jack", "lName" => "Smith"],
        ["fName" => "Bruce", "lName" => "Lee"]];

$arrFnames = array_map(function($e) {
           return $e["fName"];

},$arr);

var_dump($arrFnames);

See live code.

Each element of $arr is an array of first and last names. The anonymous function which serves as a callback returns the value of the element containing the first name.