php数组里面嵌套数_使用PHP展平嵌套数组

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 15:50   2361   0

php数组里面嵌套数

While browsing the MooTools 1.2 source code, I found Array's flatten() method. The flatten() method takes nested arrays and "flattens" them all into one array. I asked myself how I could do that using PHP. The following is what I came up with.

浏览MooTools 1.2源代码时,我发现了Array的flatten()方法。 flatten()方法采用嵌套数组,并将它们全部“展平”为一个数组。 我问自己如何使用PHP做到这一点。 以下是我想到的。

PHP (The PHP)


$myarray = array('a', 'b', array(array(array('x'), 'y', 'z')), array(array('p')));

function array_flatten($array,$return) {
 for($x = 0; $x <= count($array); $x++) {
  if(is_array($array[$x])) {
   $return = array_flatten($array[$x], $return);
  }
  else {
   if(isset($array[$x])) {
    $return[] = $array[$x];
   }
  }
 }
 return $return;
}

$res = array_flatten($myarray, array());


结果 (The Result)


Array
(
    [0] => a
    [1] => b
    [2] => x
    [3] => y
    [4] => z
    [5] => p
)


As you can see, array_flatten() is used recursively to sniff out values from the original array. While I don't believe I've ever found myself with an array as nested as my example, it's good to know that I can extract the values if necessary.

如您所见, array_flatten()递归用于从原始数组中嗅出值。 虽然我不相信自己曾经像示例中那样嵌套过数组,但很高兴知道我可以在必要时提取值。

翻译自: https://davidwalsh.name/flatten-nested-arrays-php

php数组里面嵌套数

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP