Home >php教程 >php手册 >PHP多维数组生成统一下标索引方法

PHP多维数组生成统一下标索引方法

WBOY
WBOYOriginal
2016-06-06 19:31:441315browse

有这样一个需求:将下面这段代码: $params = Array ( [tab1] = Array ( [server] = Array ( [0] = 137 [1] =122 ) ) ); 生成如下数组: $params= Array( [tab1][server][0]=137, [tab1][server][1]=122 ); 注意了,是将多维数组中的下标进行整合成统一的索引

有这样一个需求:将下面这段代码:

$params =
Array
(
[tab1] => Array
(
[server] => Array
(
[0] => 137
[1] => 122
        )
    )
 );

生成如下数组:
$params = 
Array(
  '[tab1][server][0]' = 137,
  '[tab1][server][1]' = 122
);

注意了,是将多维数组中的下标进行整合成统一的索引。
自己写了个测试代码如下,看看大家有没有更好的建议和想法: EaglePHP

源码与演示:源码出处 演示出处

$params = array('tab1'=>
					array('server1'=>array(137, 122),
						  'server2'=>array(100,200)
					),
					'tab2'=>
					array('server3'=>array(400, 500),
						  'server4'=>array(600, 700),
						   'aaa'=>array('bbb'=>array(1,2,3))
					),
					'name' => 'dimain',
					'abc' => array(4,5,6=>array('apple', 'lizi'))
				  );
		
				  
		function test(&$params, &$tmpKeyArr, &$data){
			$i = 0;
			foreach ($params as $k=>&$v){
				$i++;
				if(is_array($v)) {
					$tmpKeyArr[] = '['.$k.']';
					test($v, $tmpKeyArr, $data);
				}else{
					$data[implode($tmpKeyArr, '').'['.$k.']'] = $v;
				}
				if(count($params) == $i) array_pop($tmpKeyArr);
			}
		}
		
		$tmpKeyArr = array();
		$data = array();
		test($params, $tmpKeyArr, $data);
		echo '<pre class="brush:php;toolbar:false">';
		print_r($data);
		print_r($params);
		echo '
';
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:插入数组但不影响原来排序Next article:php水印图类