0

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!

4
  • 2
    possible duplicate of How to Flatten a Multidimensional Array? Commented Jan 24, 2015 at 18:18
  • 2
    I think your code should work. Commented Jan 24, 2015 at 18:21
  • And what's the result of you recent try? Commented Jan 24, 2015 at 18:21
  • your recursive loop should work, check your variables data or share the content of $newArray after the code has run Commented Jan 24, 2015 at 18:30

2 Answers 2

3

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>";
Sign up to request clarification or add additional context in comments.

2 Comments

This seems to return similar results to the original array
Correction, typo on my end passing back a variable to the function. Thank you for posting this response.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.