what is the easiest way to change this array to 1D array
what is the easiest way to change this array to 1D array, i can do that using for loop or foreach, but i'm curious to check if there is an easier way. THANKS
Array
(
[0] => Array
(
[id] =>开发者_StackOverflow社区; 1
)
[1] => Array
(
[id] => 2
)
[2] => Array
(
[id] => 3
)
)
$output_ar = array_map('array_shift', $input_ar);
The array_shift()
function grabs the first key/val pair out of an array and returns the value, so applying it to each of the arrays in your top-level array, and combining the results, will result in a 1-d list of the id's.
If your arrays actually have more info than just the id field in them, then you'd probably want to define a function that specifically pulls out whatever field(s) you want and returns those, and then use that function with array_map
.
Array walk will change the original array though, so if you need a separate array, copy it first, or choose an alternative method.
function reducer($e, $i, $p){
$e = $e[$p];
}
array_walk($array, 'reducer', "id");
This function is reusable though, as you can change "id" to any other key, or numeric value (I believe) and it will do the same thing upon that array.
This will retrieve all the values and put them into a new Array.
// Initializing the Array
$arr0 ['id'] = 1;
$arr1 ['id'] = 2;
$arr2 ['id'] = 3;
$arr[0] = $arr0;
$arr[1] = $arr1;
$arr[2] = $arr2;
// Processing
$resultarray = array();
for ($i = 0; $i < count($arr); $i++){
$resultarray = array_merge(array_values($arr[$i]),$resultarray);
}
// Test Output
print_r ($resultarray);
精彩评论