循环通过具有未知数量PHP的多维数组

时间:2017-07-17 14:12:57

标签: php arrays for-loop multidimensional-array

我有一个多维数组,内部数组未知。所以它可能是4,5,6,7等。我想循环遍历多维数组并挑出每个6,7和8键。我怎么能这样做?

我的多维数组

    Array
(
    [0] => Array
        (
        [0] => Foo
        [1] => Bar
        [2] => 
        [3] =>
        [4] => 1234
        [5] => 5678
        [6] => 91011
        [7] => 20170718
        [8] => TBC
        [9] =>

    )

[1] => Array
    (
        [0] => Foo
        [1] => Foo
        [2] => Bar
        [3] =>
        [4] => 1111
        [5] => 2222
        [6] => 3333
        [7] => 4444
        [8] => 5
        [9] =>

    )


 [2] => Array
    (
        [0] => Bar
        [1] => Foo
        [2] => Bar
        [3] =>
        [4] => 7777
        [5] => 9999999
        [6] => 33433
        [7] => 24
        [8] => 5
        [9] =>

    )

因此在这个例子中有数组[0],数组[1]和数组[2]。在另一个场合,可能有阵列[15]。结束数组编号未知。无论Multi维中有多少个数组,我都想选择每个数组的第4,第5,第6和第7个元素及其值。

我目前拥有的

    foreach( $fields as $key => $field) {

         echo $fields[ $key ];

         echo "\n";

    }

ECHO的输出

  Array
  Array
  Array
  Array
  Array
  Array
  Array
  Array
  Array

如何将它放入for循环中,以便将所有4,5,6,7个元素分配给变量并退出?

1 个答案:

答案 0 :(得分:0)

尝试此功能

<?php

$array = Array
(
    0 => Array
        (
        0 => "FOO",
        1 => "BAR",
        2 => "",
        3 => "",
        4 => 1234,
        5 => 5678,
        6 => 91011,
        7 => 20170718,
        8 => "TBC",
        9 => ""
    ),
1 => Array
    (
        0 => "Foo",
        1 => "Foo",
        2 => "Bar",
        3 => "",
        4 => 1111,
        5 => 2222,
        6 => 3333,
        7 => 4444,
        8 => 5,
        9 => "",
    ),
 2 => Array
    (
        0 => "Bar",
        1 => "Foo",
        2 => "Bar",
        3 => "",
        4 => 7777,
        5 => 9999999,
        6 => 33433,
        7 => 24,
        8 => 5,
        9 => "",
    )
);

$all4567values = extract4567Elements($array);

var_dump($all4567values);
exit;
function extract4567Elements (array $array)
{
    $elements4567 = [];

    $index = 0;
    foreach ($array as $element){
        if(is_array($element)){
            $elements4567 = array_merge($elements4567, extract4567Elements($element));
        }else{
            if($index == 4 || $index == 5 || $index == 6 || $index == 7){
                $elements4567[] = $element;
            } 
        }
        $index++;
    }
    return $elements4567;
}

此输出

array(12) {
  [0]=>
  int(1234)
  [1]=>
  int(5678)
  [2]=>
  int(91011)
  [3]=>
  int(20170718)
  [4]=>
  int(1111)
  [5]=>
  int(2222)
  [6]=>
  int(3333)
  [7]=>
  int(4444)
  [8]=>
  int(7777)
  [9]=>
  int(9999999)
  [10]=>
  int(33433)
  [11]=>
  int(24)
}

查看演示(https://eval.in/833525

请注意,此函数将从更深层次的嵌套数组中提取4,5,6,7值(如果有)。