从多值数组中获取单值数组的最佳方法

从多值数组中获取单值数组的最佳方法

问题描述:

Have array like this:

Array
(
    [0] => Array
        (
            [Slot_id] => 7048,
            [name] => value
        )

    [1] => Array
        (
            [Slot_id] => 7049,
            [name] => value
        )

)

I want to get the below array form

 Slot_id => Array
    (
       [0] => 7048,
       [1] => 7049
     )

currently i am using foreach function, any other best method?

有这样的数组: p>

  Array 
(\  n [0] =>数组
(
 [Slot_id] => 7048,
 [名称] =>值
)
 
 [1] =>数组
(
 [  Slot_id] => 7049,
 [name] => value 
)
 
)
  code>  pre> 
 
 

我想获得以下数组形式

  Slot_id => 数组
(
 [0] => 7048,
 [1] => 7049 
)
  code>  pre> 
 
 

目前我正在使用 foreach code>函数,还有其他最好的方法吗? p> div>

If you are using PHP >= 5.5 then array_column is the solution:

$result = array_column($input, 'Slot_id');

For earlier versions, either manually foreach or alternatively:

  • with array_map:

    // assumes PHP 5.3 for lambda function, for earlier PHP just do foreach
    $result = array_map(function($row) { return $row['Slot_id']; }, $input);
    
  • with array_walk:

    // assumes PHP 5.4 for short array syntax, for 5.3 use array() instead of []
    $result = [];
    array_walk($input, function($row) use (&$result) { $result[] = $row['Slot_id']; });
    

Use array_column function: https://php.net/manual/fr/function.array-column.php

$subArray = array_column ($your_array, 'Slot_id');