从 PHP 多维数组获取值
Getting values from PHP multidimensional array
我有一个 Array 和上面的一样:
Array
(
[4] => Array
(
[p] => 0
[c] =>
)
[5] => Array
(
[p] => 0
[c] => gh1
)
)
我正在尝试使用 PHP 以编程方式从数组中检索 [4] 或 [5],但是如果我从数组中使用 foreach(),我将得不到所需的数字(4 和5)
使用
foreach ($array as $k) {
echo '-->' . $k->p . ' ' . $k->c . '<br/>'
}
只会显示
--> 0
--> 0 gh1
我想要这个:
--> [4] 0
--> [5] 0 gh1
有人可以帮我吗?
我想出了正确的方法:
foreach (array_keys($array) as $key) {
}
它会给我们想要的数字
这是答案:
foreach ($array as $key=>$value) {
echo '--> [' . $key . '] ' . $value["p"] . ' ' . $value["c"] . '<br/>';
}
查看这里的解释:
http://php.net/manual/en/control-structures.foreach.php
The foreach construct provides an easy way to iterate over arrays.
...
There are two syntaxes:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
...
The second form will additionally assign the current element's key to
the $key variable on each iteration.
此代码更通用,因为数组中可以有不同于 c 和 d 的其他索引。看一看。
foreach ($array as $key => $value) {
echo '--->[' . $key . '] ';
foreach($value as $info => $inside) {
echo $inside . ' ';
}
echo '<br/>';
}
我有一个 Array 和上面的一样:
Array
(
[4] => Array
(
[p] => 0
[c] =>
)
[5] => Array
(
[p] => 0
[c] => gh1
)
)
我正在尝试使用 PHP 以编程方式从数组中检索 [4] 或 [5],但是如果我从数组中使用 foreach(),我将得不到所需的数字(4 和5) 使用
foreach ($array as $k) {
echo '-->' . $k->p . ' ' . $k->c . '<br/>'
}
只会显示
--> 0
--> 0 gh1
我想要这个:
--> [4] 0
--> [5] 0 gh1
有人可以帮我吗?
我想出了正确的方法:
foreach (array_keys($array) as $key) {
}
它会给我们想要的数字
这是答案:
foreach ($array as $key=>$value) {
echo '--> [' . $key . '] ' . $value["p"] . ' ' . $value["c"] . '<br/>';
}
查看这里的解释: http://php.net/manual/en/control-structures.foreach.php
The foreach construct provides an easy way to iterate over arrays. ... There are two syntaxes:
foreach (array_expression as $value) statement
foreach (array_expression as $key => $value) statement
...
The second form will additionally assign the current element's key to the $key variable on each iteration.
此代码更通用,因为数组中可以有不同于 c 和 d 的其他索引。看一看。
foreach ($array as $key => $value) {
echo '--->[' . $key . '] ';
foreach($value as $info => $inside) {
echo $inside . ' ';
}
echo '<br/>';
}