PHP foreach 与嵌套数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3684463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:41:38  来源:igfitidea点击:

PHP foreach with Nested Array?

phparraysforeachnested

提问by noangel

I have a nested array in which I want to display a subset of results. For example, on the array below I want to loop through all the values in nested array[1].

我有一个嵌套数组,我想在其中显示结果的子集。例如,在下面的数组中,我想遍历嵌套数组 [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
        )
    )
)

I was trying to use the foreach function but I cannot seem to get this to work. This was my original syntax (though I realise it is wrong).

我试图使用 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;
}

I was trying to avoid a variable compare on whether the key is the same as the key I want to search, i.e.

我试图避免对密钥是否与我要搜索的密钥相同进行变量比较,即

foreach ($tmpArray as $key => $value) {
  if ($key == 1) {
    echo $value;
  }
}

Any ideas?

有任何想法吗?

回答by Alex

If you know the number of levels in nested arrays you can simply do nested loops. Like so:

如果您知道嵌套数组中的级别数,您可以简单地进行嵌套循环。像这样:

//  Scan through outer loop
foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

if you do not know the depth of array you need to use recursion. See example below:

如果您不知道数组的深度,则需要使用递归。请参阅下面的示例:

//  Multi-dementional Source Array
$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(
            7,
            8,
            array("four", 9, 10)
    ))
);

//  Output array
displayArrayRecursively($tmpArray);

/**
 * Recursive function to display members of array with indentation
 *
 * @param array $arr Array to process
 * @param string $indent indentation string
 */
function displayArrayRecursively($arr, $indent='') {
    if ($arr) {
        foreach ($arr as $value) {
            if (is_array($value)) {
                //
                displayArrayRecursively($value, $indent . '--');
            } else {
                //  Output
                echo "$indent $value \n";
            }
        }
    }
}


The code below with display only nested array with values for your specific case (3rd level only)

下面的代码仅显示带有特定情况值的嵌套数组(仅限第 3 级)

$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(7, 8, 9))
);

//  Scan through outer loop
foreach ($tmpArray as $inner) {

    //  Check type
    if (is_array($inner)) {
        //  Scan through inner loop
        foreach ($inner[1] as $value) {
           echo "$value \n";
        }
    }
}

回答by Pratik Sawant

foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

回答by 2ndkauboy

Both syntaxes are correct. But the result would be Array. You probably want to do something like this:

两种语法都是正确的。但结果会是Array。你可能想做这样的事情:

foreach ($tmpArray[1] as $value) {
  echo $value[0];
  foreach($value[1] as $val){
    echo $val;
  }
}

This will print out the string "two" ($value[0]) and the integers 4, 5 and 6 from the array ($value[1]).

这将打印出字符串 "two" ($value[0]) 和数组 ($value[1]) 中的整数 4、5 和 6。

回答by Bahman

As I understand , all of previous answers , does not make an Array output, In my case : I have a model with parent-children structure (simplified code here):

据我了解,以前的所有答案都不会产生数组输出,就我而言:我有一个带有父子结构的模型(此处为简化代码):

public function parent(){

    return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
}


public function children()
{

    return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
}

and if you want to have all of children IDs as an Array , This approach is fine and working for me :

如果您想将所有儿童 ID 作为数组,这种方法很好,对我有用:

public function allChildren()
{
    $allChildren = [];
    if ($this->has_branch) {

        foreach ($this->children as $child) {

            $subChildren = $child->allChildren();

            if (count($subChildren) == 1) {
                $allChildren  [] = $subChildren[0];
            } else if (count($subChildren) > 1) {
                $allChildren += $subChildren;
            }
        }
    }
    $allChildren  [] = $this->id;//adds self Id to children Id list

    return $allChildren; 
}

the allChildren() returns , all of childrens as a simple Array .

allChildren() 返回,所有孩子都作为一个简单的 Array 。