Wednesday, 29 August 2018

PHP: Converting a multidimensional array to a single dimension

I have an array like this :

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" )
)

But I would like to flatten it, so its returns:
Array (
  fa-glass => "\f000",
  fa-music => "\f001",
  fa-search => "\f002",
  fa-envelope-o => "\f003",
  fa-heart => "\f004",
  fa-star => "\f005"
)

I've tried a few recursive functions, but can't seem to nail it down right. The most recent that I did try was :
$newArray = array();
foreach($bootstrap_icon_array as $array) {
 foreach($array as $k=>$v) {
   $newArray[$k] = $v;
 }
}

The results of that function is :
Array (
  [fa-glass ] => Array ( [0] => glass [1] => "\f000" )
  [fa-music ] => Array ( [0] => music [1] => "\f001" )
  [fa-search ] => Array ( [0] => search [1] => "\f002" )
  etc...
)

Thanks for the help!

There are many ways to do it,Try this way simply
$result = call_user_func_array('array_merge', $array);

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

0 comments:

Post a Comment