PHP:将多维数组转换为单维

时间:2015-01-24 18:17:28

标签: php arrays recursion multidimensional-array

我有一个这样的数组:

Array ( 
  [0] => Array ( [fa-glass ] => "\f000" ) 
  [1] => Array ( [fa-music ] => "\f001" ) 
  [2] => Array ( [fa-search ] => "\f002" ) 
  [3] => Array ( [fa-envelope-o ] => "\f003" ) 
  [4] => Array ( [fa-heart ] => "\f004" ) 
  [5] => Array ( [fa-star ] => "\f005" ) 
)

但我想压扁它,所以它的回报:

Array (
  fa-glass => "\f000",
  fa-music => "\f001",
  fa-search => "\f002",
  fa-envelope-o => "\f003",
  fa-heart => "\f004",
  fa-star => "\f005"     
)

我尝试了一些递归函数,但似乎无法正确指出它。我最近尝试的是:

$newArray = array();
foreach($bootstrap_icon_array as $array) {
 foreach($array as $k=>$v) {
   $newArray[$k] = $v;
 }
}

该功能的结果是:

Array ( 
  [fa-glass ] => Array ( [0] => glass [1] => "\f000" ) 
  [fa-music ] => Array ( [0] => music [1] => "\f001" ) 
  [fa-search ] => Array ( [0] => search [1] => "\f002" ) 
  etc...
)

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

有很多方法可以做到这一点,只需尝试这种方式

$result = call_user_func_array('array_merge', $array);

echo "<pre>";
print_r($result);
echo "</pre>";

答案 1 :(得分:0)

看起来我的代码工作正常,但是我没有传回数组中的值,而是重新传回数组。

示例:

   $newArray[] = $array;

而不是

  $newArray[] = $array[1];

我的愚蠢错误。