我有以下数组
array ( 1 => array ( 't' => array ( 0 => 't1',1 => 't2',2 => 't3',),'c' => array ( 0 => 'c1',1 => 'c2',2 => 'c3','d' => array ( 0 => 'd1',1 => 'd2',2 => 'd3',2 => array ( 'j' => array ( 0 => 'j1',1 => 'j2',2 => 'j3','m' => array ( 0 => 'm1',1 => 'm2',2 => 'm3','n' => array ( 0 => 'n1',1 => 'n2',2 => 'n3',)
我需要输出
array( 1=>array( 't-j'=>array('t1-j1','t2-j2','t3-j3'),'c-m'=>array('c1-m1','c2-m2','c3-m3'),'d-n'=>array('d1-n1','d2-n2','d3-n3') ) );
而我所做的就是
$i = 0; $res = []; foreach($arr[1] as $key => $value){ foreach($arr[2] as $k => $v){ $res[$key.'-'.$k][] = $value[$i].'-'.$v[$i]; } $i++; }
但是给我这样的东西呢?
Array ( [t-j] => Array ( [0] => t1-j1 ) [t-m] => Array ( [0] => t1-m1 ) [t-n] => Array ( [0] => t1-n1 ) [c-j] => Array ( [0] => c2-j2 ) [c-m] => Array ( [0] => c2-m2 ) [c-n] => Array ( [0] => c2-n2 ) [d-j] => Array ( [0] => d3-j3 ) [d-m] => Array ( [0] => d3-m3 ) [d-n] => Array ( [0] => d3-n3 ) )
这对我来说是个窍门:
$array1 = $arr[1]; $array2 = $arr[2]; $result = combineArray($array1,$array2); var_dump($result); function combineArray($array1,$array2) { $res = []; foreach ($array1 as $key => $value) { $otherArray = array_splice($array2,1 ); $otherKey = array_keys($otherArray)[0]; $smallerResult = array(); foreach ($value as $smallerKey => $smallerValue) { $smallerResult[] = $smallerValue . '-' . $otherArray[$otherKey][$smallerKey]; } $res[$key . '-' . $otherKey] = $smallerResult; } return $res; }
我得到的输出如下:
array(3) { 't-j' => array(3) { [0] => string(5) "t1-j1" [1] => string(5) "t2-j2" [2] => string(5) "t3-j3" } 'c-m' => array(3) { [0] => string(5) "c1-m1" [1] => string(5) "c2-m2" [2] => string(5) "c3-m3" } 'd-n' => array(3) { [0] => string(5) "d1-n1" [1] => string(5) "d2-n2" [2] => string(5) "d3-n3" } }