EHerman
EHerman

Reputation: 1892

PHP: Converting multidimensional array to 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!

Upvotes: 0

Views: 73

Answers (2)

EHerman
EHerman

Reputation: 1892

It appears my code was working properly, but instead of passing back in a value split from an array, I was re-passing back in the array.

Example :

   $newArray[] = $array;

instead of

  $newArray[] = $array[1];

Stupid mistake on my end.

Upvotes: 0

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

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

Upvotes: 3

Related Questions