PHP — 如何确定子数组的父数组的数量?
我对数组不太擅长,但我需要确定如何计算子数组的父数组数量,以便确定缩进以将其显示为 SELECT 中的选项。
那么,如果我有这个数组:
array(
'World'=>array(
'North America'=>array(
'Canada'=>array(
'City'=>'Toronto'
)
)
)
);
我将如何确定“城市”有多少个父级,以便将其转换为我想要用作缩进的空格数?
感谢您的任何帮助。
编辑:让我们看看我是否可以更好地解释自己:
我有这段代码用于构建 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);
所以,我正在尝试确定如何获取父母的数量为了在这一行的标题之前添加空格:
$html .= $value['title'];
就像:
$html .= " " . $value['title'];
但是,我不知道如何计算出要添加多少个空格。
希望这一点更加清楚。
感谢迄今为止的任何帮助。
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 .= " " . $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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
适合参观:
For visiting:
出色地。从顶部你正在处理的是一个多维数组。
您可以在数组的每个级别上运行 foreach 计数,并为 foreach 循环的每个级别使用返回的计数 +1。
我不确定这是否回答了您的问题,但我正在尝试确切地了解您想要实现的目标。
Well. Off the top what you are dealing with is a multi dimensional array.
You could run a count w/ foreach on each level of the array, and use the count number returned +1 for each level the foreach loops through.
I'm not sure if this answers your question, but I am trying to see exactly what it is you are trying to achieve.
由于您已经在使用递归函数来显示该数据,因此您可以扩展您的函数。不需要多次遍历数组:
As you are already using a recursive function to display that data, you can just extend your function. There is no need to traverse the array more often than one time:
尝试以下操作..您的解决方案在我的脑海中尖叫着递归。它有点难看,但似乎有用
Try the following.. Your solution screams for recursion in my mind. Its a bit ugly but it seems to work