duanliang789262 2011-02-04 02:20
浏览 25
已采纳

PHP - 如何确定子数组的父项数?

I'm not so strong with arrays but I need to determine how to count the number of parents a child array has in order to determine the indenting to display it as an option in a SELECT.

So, if I have this array:

array(
      'World'=>array(
            'North America'=>array(
                  'Canada'=>array(
                       'City'=>'Toronto'
                   )
            )
      )
);

How would I go about determining how many parents 'City' has in order to translate that into the number of spaces I want to use as an indent?

Thanks for any help.

EDIT: Let's see if I can explain myself better:

I have this code I'm using to build the OPTIONS list for a SELECT:

function toOptions($array) {

    foreach ($array as $key=>$value) {
        $html .= "<option value=\"" . $key . "\" >";

        $html .=  $value['title'];

        $html .= "</option>";

        if (array_key_exists('children', $value)) {
            $html .= toOptions($value['children']);
        }

    }

    return $html;

}

print toOptions($list);

So, I'm trying to determine how to get the number of parents in order to add spaces before the title in this line:

$html .=  $value['title'];

Like:

$html .= "&nbsp;&nbsp;&nbsp;" . $value['title'];

But, I'm not sure how to figure out how many spaces to add.

Hopefully this is more clear.

Thanks for any help so far.

  • 写回答

4条回答 默认 最新

  • doushou7169 2011-02-04 02:35
    关注
    $x = array(
          'World'=>array(
                'North America'=>array(
                      'Canada'=>array(
                           'City'=>'Toronto'
                       )
                )
          )
    );
    
    // This function do something with the key you've found in the array
    function visit($name, $depth)
    {
        echo $name . ' has ' . $depth . ' parents.'; 
    }
    
    // This function visits all the contents aff $array
    function find_recursive($array, $depth = 0)
    {
        if (is_array($array)) {
            foreach ($array as $k => $value) {
                visit($k, $depth + 1);
                find_recursive($array, $depth + 1);
            }
        }
    }
    

    For visiting:

    find_recursive($x);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题