php 从数组树中获取级别数组

发布于 2024-09-24 21:21:40 字数 670 浏览 3 评论 0原文

我有下一个数组: 大批 ( [1000] =>大批 ( [pv] => 81 )

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

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

        [pv] => 72
    )

) 我想从中创建新数组,如下所示:

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)
)

生成是数组深度的一个级别。有很多级别。 谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

是伱的 2024-10-01 21:21:40

有创意...

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);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文