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

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 19:31:44
Original
1347 people have browsed it

有这样一个需求:将下面这段代码: $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 '
Copy after login
';
source:php.cn
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template