2014-04-08 54 views
2

我有一个数组,每个数组包含4个数组。如何在PHP中压扁数组?

array(4) { 
    [0]=> 
    array(1) { 
    ["email"]=> 
    string(19) "[email protected]" 
    } 
    [1]=> 
    array(1) { 
    ["email"]=> 
    string(19) "[email protected]" 
    } 
    [2]=> 
    array(1) { 
    ["email"]=> 
    string(19) "[email protected]" 
    } 
    [3]=> 
    array(1) { 
    ["email"]=> 
    string(19) "[email protected]" 
    } 
} 

什么是最好的(=最短,PHP本身的首选功能)的方式实现平坦化阵列,使其只包含电子邮件地址作为值:

array(4) { 
    [0]=> 
    string(19) "[email protected]" 
    [1]=> 
    string(19) "[email protected]" 
    [2]=> 
    string(19) "[email protected]" 
    [3]=> 
    string(19) "[email protected]" 
} 

回答

6

在PHP 5.5你有array_column

$plucked = array_column($yourArray, 'email'); 

否则,请与array_map

$plucked = array_map(function($item){ return $item['email'];}, $yourArray); 
+2

或者如果你没有PHP 5.5,你可以使用官方函数 – Populus

+0

的作者'array_column'的https://github.com/ramsey/array_column的用户空间实现,这正是我所需要的。谢谢! –

+0

其中一天,我需要学习array_map ... – Mike

1

可以使用RecursiveArrayIterator。这甚至可以使多嵌套数组扁平化。

<?php 
$arr1=array(0=> array("email"=>"[email protected]"),1=>array("email"=>"[email protected]"),2=> array("email"=>"[email protected]"), 
    3=>array("email"=>"[email protected]")); 
echo "<pre>"; 
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr1)); 
$new_arr = array(); 
foreach($iter as $v) { 
    $new_arr[]=$v; 
} 
print_r($new_arr); 

OUTPUT:

Array 
(
    [0] => [email protected] 
    [1] => [email protected] 
    [2] => [email protected] 
    [3] => [email protected] 
) 
+0

也很好的方法,但我更喜欢@ moonwave99的答案,因为它是一个精益的单线程。 –

+0

@GottliebNotschnabel,没问题。我建议这是一个广义的解决方案,因为即使在多维数组上它也能工作。 –

+1

非常好,这可能有助于其他情况下的人。 –