【问题标题】:PHP Looping through an array with strings AND an array insidePHP循环遍历带有字符串的数组和里面的数组
【发布时间】:2010-10-22 01:45:35
【问题描述】:

这是一个基本的循环问题,但有一个转折,所以我很可能错过了一些简单的东西 - 提前道歉......

我正在尝试从数组 $testoutput 中提取结果 - 该数组填充了 3 个数组:

运行以下代码:

foreach ($testoutput as $ID => $Array) {
   echo $Array . "<BR>";
}

返回:

ARRAY
ARRAY
ARRAY

使用以下代码添加第二个嵌套循环:

foreach ($testoutput as $ID => $Array) {
   foreach ($Array as $ID => $L1item) {
      echo $L1item . "<BR>";
   }
}

结果:

String1a
String1b
String1c
ARRAY
String2a
String2b
String2c
ARRAY
String3a
String3b
String3c
ARRAY

我可以重新调整所有上述字符串,但是,我不知道如何从嵌套数组的第 3 级返回值。

有没有简单的方法可以做到这一点?

非常感谢。

【问题讨论】:

  • 仅供参考,数组是 PHP 中的保留字,最好不要将其用作变量名。
  • 您正在重新使用$ID 变量。不要那样做。

标签: php arrays loops nested-loops


【解决方案1】:

您可以使用array_map

$testoutput = array('x', array('y', 'z', array('1', '2', '3')));
function output($element) {
    if(is_array($element)) {
       array_map('output', $element); //RECURSION
       return;
    }
    echo $element;
}
array_map('output', $testoutput);   

或者,如果您愿意,可以使用array_walk_recursive

function output(&$value, $index) {
    echo $value;
}
array_walk_recursive($testoutput, 'output');

【讨论】:

  • 抱歉,我在您编辑之前对您的代码进行了评论。更新的版本是正确的。
  • 不正确:cl.ly/ad4a1bf86ce85c39aff4 - 你在我发表评论后 3 分钟编辑了它。
  • 我当时责怪服务器松懈,因为我没有看到任何更新;)对不起
【解决方案2】:

试试这个:

/** 
 * array nested_array_map(callback $callback, array $array)
 * Warning - doesn't check for recursion, 
 *           therefore child arrays shouldn't contain references to any of parent level arrays
 *
 * @param $callback, function
 * @param $array, array of elements to map the function to
 * @return array
 */
function nested_array_map($callback, $param) {
    if (!is_array($param)) {
        return call_user_func($callback, $param);
    }

    $result = array();
    foreach ($param as $index => $value) {
        $result[$index] = nested_array_map($callback, $value);
    }
    return $result;
}

function echo_value($value) {
    echo "$value\n";
    return $value;
}

$test = array(
    '1st level'
    ,array(
        '2nd level'
        ,array(
            '3rd level'
        )
        ,'2nd level'
    )
    ,array(
        '2nd level'
    )
    ,'1st level'
);

$result = nested_array_map('echo_value', $test);

【讨论】:

    【解决方案3】:
    foreach ($testoutput as $key1 => $value1) {
       foreach ($value1 as $key2 => $value2) {
          if(is_array($value2))
          {
                  foreach ($value2 as $key3 => $value3) {
                              echo $value3;
                  }
          }
          else
          {
                  echo $value2;
          }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-31
      • 2023-03-23
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2019-09-07
      相关资源
      最近更新 更多