I had a similar problem and was glad to find this post. However, the solutions presented only work for 2 levels and do not work for a multi-dimensional array with any number of levels. I need a solution that could work for an array with any dimension and find the first keys of each level.
After a bit of work, I found a solution that might be useful for someone else, and so I included my solution in this post.
Here is an example starting array:
$myArray = array( 'referrer' => array( 'week' => array( '201901' => array( 'Internal' => array( 'page' => array( 'number' => 201, 'visits' => 5 ) ), 'External' => array( 'page' => array( 'number' => 121, 'visits' => 1 ) ), ), '201902' => array( 'Social' => array( 'page' => array( 'number' => 921, 'visits' => 100 ) ), 'External' => array( 'page' => array( 'number' => 88, 'visits' => 4 ) ), ) ) ) );
Since this function should display all the first keys regardless of the size of the array, this assumes a recursive function, and my function looks like this:
function getFirstKeys($arr){ $keys = ''; reset($arr); $key = key($arr); $arr1 = $arr[$key]; if (is_array($arr1)){ $keys .= $key . '|'. getFirstKeys($arr1); } else { $keys = $key; } return $keys; }
When a function is called using code:
$xx = getFirstKeys($myArray); echo '<h4>Get First Keys</h4>'; echo '<li>The keys are: '.$xx.'</li>';
exit:
Get the first keys
- Keys: Referrer | week | 201901 | internal | page | number
I hope this saves someone some time if they run into a similar problem.
Clinton
source share