2017-02-27 49 views
-1

我有一个数组如下(的var_dump下图):返回数组值通过密钥

array (size=3) 
    'Test Field 1' => 
    array (size=1) 
     0 => string 'foo' (length=3) 
    'Test Field 2' => 
    array (size=3) 
     0 => string 'bar' (length=3) 
     1 => string 'foobar' (length=6) 
     2 => string 'barfoobar' (length=9) 
    'Test Field 3' => 
    array (size=2) 
     0 => string 'barfoo' (length=6) 
     1 => string 'foobarfoobar' (length=12) 

我想输出的数据,如下所示通过密钥分组:

  • 试验字段1: FOO
  • 试验字段2:巴
  • 试验字段3:barfoo
  • 试验字段2:foobar的
  • 试验字段3:foobarfoobar
  • 试验字段2:barfoobar

基本上,所有的0键组合在一起的,则1个键,则2个键等

阵列赢得不要总是这样设置,这意味着每个数组可能有更多的元素,或者可能只有一个,所以它需要能够动态填充。

一个典型的foreach循环给我的数据输出如下(不是我想要的):

  • 测试场1:富
  • 测试场2:巴
  • 测试场2:foobar的
  • 测试字段2:barfoobar
  • 试验字段3:barfoo
  • 试验字段3:foobarfoobar
+1

获取最大元素的尺寸。然后从0循环到该大小,并在该循环内通过顶级元素,如果它存在,则打印它的第N个元素。 – Barmar

+0

谢谢!我认为用它的话来说,并不是我自己帮助我解决了这个问题。 – ScottD

+0

也分享您的代码? – C2486

回答

0

上面的var_dump来自变量$output。显示为上述的数据,我做了以下:

$max = max(array_map('count', $output)); // get the max number of keys in the array 
$repeat = 0; //set to start with 0 key 
for($repeat; $repeat<=$max; $repeat++){ 
    foreach($output as $key => $values){ //loop through the $output 
     if (isset($values[$repeat])){ // check if this exists 
      echo $key . ': ' . $values[$repeat] . '<br />'; //display the key/values as needed 
     } 
    } 
} 
0

这个被测试代码

$input = [ 
    'Test Field 1' => [ 
     'foo', 
    ], 
    'Test Field 2' => [ 
     'bar', 
     'foobar', 
     'barfoobar', 
    ], 
    'Test Field 3' => [ 
     'barfoo', 
     'foobarfoobar', 
    ], 
]; 

function recursive_print($input) 
{ 
    foreach ($input as $k => &$v) { 
     echo "\n"; 
     echo $k. ':' . array_shift($v); 

     if (!$v) { 
      unset($input[$k]); 
     } 
    } 


    if ($input) { 
     recursive_print($input); 
    } 
} 

recursive_print($input);