How exactly can I apply array_column() to always get the first column of an array instead of getting the column by name?
I am seeking something like this is:
array_column($array,[0])
instead of:
array_column($array,"key");
Try
array_column($array, array_shift(array_keys($array)));
from Return first key of associative array in PHP
Hope can help! :)
While array_column() will allow you to target a column using an integer, it needs to be an existing integer key. Otherwise, you will need to determine the first subarray's first key to gain access to that column dynamically.
Code: (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
Output:
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',
)
If you use a loop or functional iterator, you can call current() or reset() to access the first element of each row, but if those first elements have different keys, then this is not technically a column of data. See what I mean in the demo -- you inadvertently grab values from different keys.
var_export(array_map('current', $array));
// ['bar1', 'bar2', 'zero']
...but current() only gets you the first column. For any column by position starting from 0, re-index all rows before calling array_column(). Demo
var_export(
array_column(
array_map(array_values(...), $array),
1
)
);
Here's a one-liner:
array_column($array, array_keys(array_values($array)[0])[0])
First it takes the first record of the multidimensional array:
array_values($array)[0]
The from that record, it gets the keys, and you can index any of the keys:
array_keys(array_values($array)[0])[0] # first column
array_keys(array_values($array)[0])[1] # second column
array_keys(array_values($array)[0])[2] # third column
array_keys(array_values($array)[0])[3] # fourth column
That gives you the name of the key by index that you can plug in array_column()
array_column($array, array_keys($array)[0]);array_keys($array)[0]is the first index name. Do you have different column names in each row?