Skip to content

Instantly share code, notes, and snippets.

@sany2k8
Created February 8, 2017 06:49
Show Gist options
  • Save sany2k8/5a8af653730d3adb0c6bd3e9596fd3ec to your computer and use it in GitHub Desktop.
Save sany2k8/5a8af653730d3adb0c6bd3e9596fd3ec to your computer and use it in GitHub Desktop.
Convert a 2-D array to 1-D array
<?php
/**
* Created by PhpStorm.
* User: Computer Source
* Date: 12/12/14
* Time: 3:56 PM
*/
$array = array(
array(554 => "a"),
array(561 => "b"),
array(574 => "c")
);
$array = array(
array(554 => array(1,3,2)),
array(561 => array(1,9,2)),
array(574 => array(5,3,2))
);
$singleDimension=array_reduce($array,function($array,$item){return $array+$item;},array());
print '<pre>';
print_r($singleDimension);
print '</pre>';
$singleDimension2=call_user_func_array('array_merge',$array);
print '<pre>';
print_r($singleDimension2);
print '</pre>';
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $k=>$v){
$singleDimension3[$k]=$v;
}
print '<pre>';
print_r($singleDimension3);
print '</pre>';
$result = array();
array_walk_recursive($array,function($v, $k) use (&$result){ $result[] = $v; });
print '<pre>';
print_r($result);
print '</pre>';
$oneDimensionalArray = array_map('current', $array);
print '<pre>';
print_r($result);
print '</pre>';
$oneDimensionalArray = array_column($array);
print '<pre>';
print_r($oneDimensionalArray);
print '</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment