I have array like the following
Array ( [0] => Array ( [0] => 5 ) [1] =>开发者_如何转开发; Array ( [0] => 6 [1] => 7 ) )
Now I want only values of this two dimensional array
The result should be array(5,6,7)
Bit of a hack/neat trick depending on how you look at it ;)
$result = call_user_func_array('array_merge', $a);
You're looking for array_values()
which returns an array of all array values, sans-keys.
http://php.net/manual/en/function.array-values.php
Update:
Alternatively for an already multi-dimensional array, you can use the following recursive function (borrowed from http://davidwalsh.name/flatten-nested-arrays-php):
function array_flatten($array,$return)
{
for($x = 0; $x <= count($array); $x++)
{
if(is_array($array[$x]))
{
$return = array_flatten($array[$x],$return);
}
else
{
if($array[$x])
{
$return[] = $array[$x];
}
}
}
return $return;
}
Something like this
array_merge($a[0], $a[1]);
function flattenArray($array) {
$flattened = array();
foreach($array as $value) {
if (is_array($value)) {
$flattened = array_merge($flattened, flattenArray($value));
} else {
$flattened[] = $value;
}
}
return $flattened;
}
$array = array(1, array(2, 3), array(4, array(5, 6)));
var_dump($array, flattenArray($array));
Output
array(3) {
[0]=>
int(1)
[1]=>
array(2) {
[0]=>
int(2)
[1]=>
int(3)
}
[2]=>
array(2) {
[0]=>
int(4)
[1]=>
array(2) {
[0]=>
int(5)
[1]=>
int(6)
}
}
}
array(6) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
[5]=>
int(6)
}
CodePad.
$result = array();
foreach($parentArray as $pa)
{
if(is_array($pa))
$result= array_merge($result, $pa);
else
$result[] = $pa;
}
Use $result
.
精彩评论