此问题已在此处有答案:
Is there a function to extract a 'column' from an array in PHP?(15个回答)
昨天关门了。
我有一个嵌套数组,我想在其中显示结果的子集。例如,在下面的数组中,我想循环遍历嵌套数组[1]中的所有值。
Array
(
[0] => Array
(
[0] => one
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
[1] => Array
(
[0] => two
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
)
[2] => Array
(
[0] => three
[1] => Array
(
[0] => 7
[1] => 8
[2] => 9
)
)
)
我试图使用foreach函数,但我似乎不能让这个工作。这是我最初的语法(尽管我意识到它是错误的)。
$tmpArray = array(array("one",array(1,2,3)),array("two",array(4,5,6)),array("three",array(7,8,9)));
foreach ($tmpArray[1] as $value) {
echo $value;
}
我试图避免一个变量比较的关键是否是相同的关键,我想搜索,即。
foreach ($tmpArray as $key => $value) {
if ($key == 1) {
echo $value;
}
}
有什么想法吗
5条答案
按热度按时间1zmg4dgp1#
如果你知道嵌套数组的层数,你可以简单地做嵌套循环。就像这样:
如果你不知道数组的深度,你需要使用递归。参见以下示例:
下面的代码仅显示嵌套数组,其中包含特定情况下的值(仅限第3级)
dgiusagp2#
xmjla07d3#
两种语法都是正确的。但结果是
Array
。你可能想做这样的事情:这将打印出字符串“two”($value[0])和数组($value[1])中的整数4、5和6。
nhaq1z214#
据我所知,所有以前的答案,不使数组输出,在我的情况下:我有一个父子结构的模型(这里有简化的代码):
如果你想让所有的子ID都作为一个数组,这种方法很好,对我来说很有效:
allChildren()返回一个简单的数组。
bbuxkriu5#
我有一个嵌套的值数组,需要确保这些值都不包含
&
,所以我创建了一个递归函数。