开发者

Get all values in one array PHP

开发者 https://www.devze.com 2023-02-19 21:45 出处:网络
I have this array: array(3) { [0]=> array(3) { [0]=> array(1) { [0]=> string(2) \"14\" } [1]=> string(2) \"12\"

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开发者_Go百科"
}

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


You could use array_walk_recursive:

$output = array();
array_walk_recursive($inputArray,
   create_function('$val, $key, $obj', 'array_push($obj, $val);'), &output)


$res = array();
array_walk_recursive($ar, function($v, $k, $res) {
  $res[] = $v;
}, &$res);


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


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消