0

I have this array:

  array(3) {
  [0]=>
  array(3) {
    [0]=>
    array(1) {
      [0]=>
      string(2) "14"
    }
    [1]=>
    string(2) "12"
    [2]=>
    string(2) "13"
  }
  [1]=>
  string(2) "10"
  [2]=>
  string(2) "11"
}

is there some PHP function with output all values in one string. Like this:

    array(5){
    [0]=>
    string(2) "14"

    [1]=>
    string(2) "12"

    [2]=>
    string(2) "13"

     [3]=>
    string(2) "11"
}
1
  • Please no more :O Loop through entire array and fetch string type data in new 1D array. Commented Mar 27, 2011 at 15:42

6 Answers 6

2

You could use array_walk_recursive:

$output = array();
array_walk_recursive($inputArray,
   create_function('$val, $key, $obj', 'array_push($obj, $val);'), &output)
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work for me with php 5.3.3. Are you sure you can pass $output by value instead of by reference?
1
$res = array();
array_walk_recursive($ar, function($v, $k, $res) {
  $res[] = $v;
}, &$res);

3 Comments

this only works in php 5.3, right? (confused about the use of function)
Before 5.3, you'd write create_function('$v, $k, $res', '$res[] = $v;');
. the new notation is better. (still stuck at 5.2 here)
1

Another option is to make use of some of the SPL's iterators1,2 and the iterator_to_array()3 function, to save yourself the work of anonymous callbacks.

$leaves = iterator_to_array(
    new RecursiveIteratorIterator(
        new RecursiveArrayIterator($array)
    ),
    FALSE
);

Refs

  1. RecursiveArrayIterator http://php.net/recursivearrayiterator
  2. RecursiveIteratorIterator http://php.net/recursiveiteratoriterator
  3. iterator_to_array() http://php.net/iterator_to_array

Comments

0
function flatten_array(array $a) 
{
   array_walk_recursive($a, function($v) use(&$r) { $r[] = $v; });
   return $r;
}

Comments

-1

No, there isn't. You will have to write your own.

Comments

-1

You won't get exactly what you want, but you could see array_walk_recursive.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.