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

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值