Reputation: 70
I have a multidimensional array called $test
:
Array (
[First item] => Array (
[screen] => 2
[1] => 2
[2] => 2
[3] => 2
[4] => 2
)
[Second Item] => Array (
[screen] => 3
[1] => 3
[2] => 3
[3] => 3
[4] => 3
)
)
I am trying to get the keys: screen
, 1
, 2
, 3
, and 4
.
They are the same for First item
and Second item
. Do you know how I can loop through this array to get those values? So, basically getting the keys for the first array in my multidimensional array. Thank you!
Upvotes: 1
Views: 3390
Reputation: 24740
It depends on what you are trying to archive:
$test = Array (
"First item" => Array (
"screen" => 2,
1 => 2,
2 => 2,
3 => 2,
4 => 2,
),
"Second Item" => Array (
"screen" => 3,
1 => 3,
2 => 3,
3 => 3,
4 => 3,
)
);
To get all the keys
$vals = [];
foreach($test as $k=>$v){
$vals = array_merge($vals, array_keys($v));
}
this will yield you:
Array
(
[0] => screen
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => screen
[6] => 1
[7] => 2
[8] => 3
[9] => 4
)
Separated in another multidimensional array:
foreach($arr as $k=>$v){
$vals[] = array_keys($v);
}
Only the unique keys:
foreach($test as $k=>$v){
$vals = array_unique(array_merge($vals, array_keys($v)));
}
Upvotes: 0
Reputation: 91744
That would be something like:
$keys = array_keys(reset($your_array));
reset()
gets the first value of your array and array_keys()
the keys of the resulting array.
You might want to split it in two lines using a temporary variable to avoid strict warnings.
Upvotes: 1
Reputation: 5151
How about this:
$keys = array_keys($test['First item']);
Or if you want to do it manually:
$keys = array();
foreach($test['First item'] as $key => $value) {
$keys[] = $key;
}
Upvotes: 1