PHP数组

数组操作方法合集

Watermoe

多维数组转换成一维数组

//递归法
$arr = [

  'name' => ['water', 'moe'],
  'age' => [20,21],
  'adress' => ['guangdong','zhanjiang'],
  'hello php'
];

function flatten_array(array $items, array $flattend=[])
{
  foreach($items as $item){
    if(is_array($item)){
       $flattend = flatten_array($item, $flattend);
       continue;
    }
     $flattend[] = $item;
  }
  return $flattend;
}

var_dump(flatten_array($arr,[]));

//php自带类库 RecursiveArrayIterator 和 RecursiveIteratorIterator

$flattend = new RecursiveArrayIterator($arr);
$flattend = new RecursiveIteratorIterator($flattend);
$flattend = iterator_to_array($flattend, false);
var_dump($flattend);