Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
2  
possible duplicate of How to Flatten a Multidimensional Array? –  Rafael 2 days ago
2  
I think your code should work. –  zairwolf 2 days ago
    
And what's the result of you recent try? –  u_mulder 2 days ago
    
your recursive loop should work, check your variables data or share the content of $newArray after the code has run –  Lupin 2 days ago

2 Answers 2

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>";
share|improve this answer
    
This seems to return similar results to the original array –  EHerman 2 days ago
    
Correction, typo on my end passing back a variable to the function. Thank you for posting this response. –  EHerman 2 days ago

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.