循环多维数组,然后检查是否在PHP中

时间:2018-10-28 16:08:44

标签: php arrays loops multidimensional-array conditional-statements

我有这个

<?php

//array[x][y] right?
$condition = array
(
array("cat","meow"),
array("cow","moo"),
array("dog","bark"),
);

//Do I need two For loops to be able to go through each array values?

if($condition==array[x]){
    echo array[y];
}
?>

我正在尝试遍历多维数组并在条件正确的情况下打印该数组。我希望我的问题不够模糊。但是我有点卡住,我不知道如何正确地遍历它们。我希望提供任何帮助或为我指明正确的方向。谢谢。

2 个答案:

答案 0 :(得分:0)

在这种情况下,您不需要两个循环,可以使用implode。
但是通常,是的,您将需要两个循环。

$condition = array
(
array("cat","meow"),
array("cow","moo"),
array("dog","bark"),
);

foreach($condition as $cond){
    echo implode(" says ", $cond) . "\n";
}

//cat says meow
//cow says moo
//dog says bark

常规方法是按您所说的循环两次。

foreach($condition as $cond){
    foreach($cond as $item){
        echo $item ." ";
    }
}

现在我考虑一下,您也可以这样做:

foreach($condition as $cond){
    echo $cond[0] . " says " . $cond[1] . "\n"; 
}

这将产生与第一个示例相同的结果。

答案 1 :(得分:0)

如果我没有误解您的问题,那么您可以使用单个foreach()循环来检查数组元素值的条件。

<?php
$array = array
    (
    array("cat","meow"),
    array("cow","moo"),
    array("dog","bark"),
);
//you can use single foreach() loop to iterate your $array
$condition = 'cat'; //demo condition
print_r($array);
foreach($array as $k=>$v){
    if($condition == $v[0]){
        echo $v[1];
    }
}
?>

演示: https://3v4l.org/k7mh0