简体   繁体   中英

php Get level array from Array Tree

I Have the next array: Array ( [1000] => Array ( [pv] => 81 )

[1101] => Array
    (
        [1102] => Array
            (
                [pv] => 33
            )

        [1103] => Array
            (
                [pv] => 15
            )

        [pv] => 72
    )

) I want to make new array from this like this:

Array(
[1000] => Array(['generation'] => 1, ['pv'] => 81)
[1101] => Array(['generation'] => 1, ['pv'] => 72)
[1102] => Array(['generation'] => 2, ['pv'] => 33)
[1103] => Array(['generation'] => 2, ['pv'] => 15)
)

Generation is a level of array's deep. There are a lot of levels. Thanks.

Be creative...

function coffee($elm, $cur_key=NULL, $level=0, &$push_arr=NULL){
   if(!is_array($push_arr)) $pusH_arr = array();
   $level++;
   foreach($elm as $key=>$val){
      if($key == 'pv'){
         $push_arr[$cur_key] = array(
             'generation' => $level,
             'pv' => $val
         );
      }
      else if(is_array($val)){
         coffee($val, $key, $level, $push_arr);
      }
      else{
         // unexpected value
      }
   }
   return $push_arr;
}
// Usage:
$normalised_array = coffee($array_from_your_question);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM