ludo1960 Posted January 12, 2019 Share Posted January 12, 2019 Hi Guys, I have got a large nested multi dimensional array, I have the following function that nearly does what I want: This is the array: Array ( [country] => Scotland .... I run it through the function below, and it finds all the nested keys and the output is Array ( [0] => country [1] .... All the keys are represented but the values are not set, how can I get the function to add the value? function array_keys_multi(array $array) { $keys = array(); foreach ($array as $key => $value) { $keys[] = $key; if (is_array($array[$key])) { $keys = array_merge($keys, array_keys_multi($array[$key])); "<br>"; } } return $keys;... } Quote Link to comment Share on other sites More sharing options...
requinix Posted January 12, 2019 Share Posted January 12, 2019 I can only assume the answer is not $array["country"]. Explain what you want to do in more detail. Quote Link to comment Share on other sites More sharing options...
ludo1960 Posted January 12, 2019 Author Share Posted January 12, 2019 (edited) Yes the answer is "Scotland" more detail: As Scotland is the the first entry in the complex array, and yes I can access it by calling echo $array(['country']) all fine and well, but as you call items further down the chain eg 'price' calling $array(['price']) returns nothing. So i came across the function above and it successfully crawls the nested and multi dimensional array retaining all the keys in a usable order e.g. $array[24] is 'price'. I would like the returned array to be $array[0]['country]=>'Scotland' and .... $array[24]['price']=>'$2,000' Does that make sense? Edited January 12, 2019 by ludo1960 Quote Link to comment Share on other sites More sharing options...
ludo1960 Posted January 14, 2019 Author Share Posted January 14, 2019 And the answer is: function FlattenMultiArray($array,$bKeepKeys=true,$key_prefix='') { $array_flattened=Array(); foreach($array as $key=>$value){ if(Is_Array($value)){ $array_flattened=Array_Merge( $array_flattened, FlattenMultiArray($value,$bKeepKeys,$key) ); } else{ if($bKeepKeys){ $array_flattened["{$key_prefix}{$key}"]=$value; } else{ $array_flattened[]=$value; } } } return $array_flattened; } Quote Link to comment Share on other sites More sharing options...
Barand Posted January 14, 2019 Share Posted January 14, 2019 It is prone to losing values if you get a clash of key values $data = [ 'A' => 1, 'B' => 2, 'C' => [ 'D' => 4, 'E' => [ 'F'=>6, 'G'=>7]], 'F' => 6 ]; results in Array ( [A] => 1 [B] => 2 [CD] => 4 [EF] => 6 [EG] => 7 [F] => 6 ) Whereas $data = [ 'EG' => 1, 'B' => 2, 'C' => [ 'D' => 4, 'E' => [ 'F'=>6, 'G'=>7]], 'F' => 6 ]; results in Array ( [EG] => 7 [B] => 2 [CD] => 4 [EF] => 6 [F] => 6 ) thus losing the first 'EG' Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.