虽然array_column() 允许您使用整数来定位列,但它必须是现有的整数键。否则,您将需要确定第一个子数组的第一个键才能动态访问该列。
代码:(Demo)
$array = [
["foo" => "bar1", "hey" => "now"],
["foo" => "bar2", "hey" => "what"],
[0 => "zero", 1 => "one"]
];
var_export(array_column($array, 'foo')); // get the column by name
echo "\n---\n";
var_export(array_column($array, 0)); // don't need to be a string
echo "\n---\n";
var_export(array_column($array, key(current($array)))); // access the first subarray, access its key
echo "\n---\n";
var_export(array_column($array, array_shift(array_keys($array)))); // this generates a Notice, and damages the array
输出:
array (
0 => 'bar1',
1 => 'bar2',
)
---
array (
0 => 'zero',
)
---
array (
0 => 'bar1',
1 => 'bar2',
)
---
Notice: Only variables should be passed by reference in /in/hH79U on line 14
array (
0 => 'zero',
)