如何访问多维数组的每个键下的所有元素。
$multi = array
(
"Abhishek" => array("Choudhary", "Bunta", "Popy"),
"Bond" => array("One", "two", "three", "four"),
"Super" => array("T1", "T2")
);
$data = array("Abhishek","Bond","Super");
for($j = 0;$j<count($data);$j++)
{
echo "<br/>Main Array Value ".$data[$j]."<br/>";
for($i = 0;$i<count($data[$j]);$i++)
{
echo "sub Value ".$multi[$data[$j]][$i]." count ".count($data[$j]) ;
}
}
现在我想遍历Abhishek,Bond和Super的每个元素,所以我们可以看到Abhishek里面有3个元素,但$ data [$ j]总是返回1.如果我增加,那么我可以访问Bunta 目前输出是 -
Main Array Value Abhishek
sub Value Bunta
Main Array Value Bond
sub Value two
Main Array Value Super
sub Value T2
,预期是:
**
Main Array Value Abhishek
sub Value choudhary
sub Value Bunta
sub Value Popy
:
:
Main Array Value Bond
sub Value two
Main Array Value Super
sub Value T2
**
免责声明:我是PHP的新手,所以可能是我的期望无效或者我错过了一些非常愚蠢的事情。
答案 0 :(得分:3)
我建议您阅读一些关于multidim数组的文章,无论如何,您的需求可以通过以下代码完成:
foreach($multi as $key => $value) {
echo "<br/>Main Array Value ".$key."<br/>";
for($i = 0; $i < sizeof($value); $i++) {
echo "sub Value ".$value[$i]." count ".sizeof($value) ;
}
}
PS:你不需要$data
数组
答案 1 :(得分:2)
使用foreach()
会更容易
foreach ($multi as $key => $subarray)
{
echo $key . '<br />';
foreach ($subarray as $subvalue)
{
echo ' - '.$subvalue . '<br />';
}
}
将输出
Abhishek
- Choudhary
- Bunta
- Popy
Bond
- One
- two
- three
- four
Super
- T1
- T2
答案 2 :(得分:1)
答案 3 :(得分:0)
试试这个:
<?php
foreach($multi as $key => $value) {
echo "<br/>Parent Value ".$key."<br/>";
for($i = 0; $ < sizeof($value); $++) {
echo "Child Value ".$value[$i]." count ".sizeof($value) ;
}
}
?>
You are using wrong syntax to access it.
答案 4 :(得分:-1)
您只需使用foreach迭代$ multi数组(如果您只想知道每个元素级别1的子元素数):
<?php
echo "<br\>multiDimensional Array<br\>";
$multi = array("Abhishek" =>array
("Choudhary",
"Bunta",
"Popy"),
"Bond" => array
("One",
"two",
"three",
"four"),
"Super" => array
("T1",
"T2")
);
foreach( $multi as $value ){
echo " count ".count($value) ;
}