2013-04-29 64 views
1

说我有一个多维的,数字零索引数组,看起来像这样:从包含元素的键的值枚举多维PHP数组上的键最优雅的方式是什么?

$oldArray = (
    0 => array("importantKey" => "1", "otherKey" => "someValue"), 
    1 => array("importantKey" => "4", "otherKey" => "someValue"), 
); 

什么是这个到下面最彻底的方法,只要我可以肯定“importantKey”

的独特性
$newArray = (
    1 => array("otherKey" => "someValue"), 
    4 => array("otherKey" => "someValue"), 
); 

的“importantKey”做一个GROUP BY子句后,从数据库检索多个行的时候,这是有用

+0

使用foreach循环并枚举一个新数组对我来说是最明显的选择,但我想知道是否有一个PHP特定函数以更优雅的方式实现这一点。 – 2013-04-29 10:46:23

+1

我会说最明显的选择!不要试图变聪明:-) – 2013-04-29 10:58:19

回答

2

ŧ ry

$newArray = array_reduce($oldArray, function($res, $val) { 
    $res[$val['importantKey']]['otherKey'] = $val['otherKey']; 

    return $res; 
}, array()); 

这是否够优雅? :)

+0

优雅确定!为了理解发生了什么,维护者goog运气:-) – 2013-04-29 10:55:38

1
$data=array(); 
foreach($oldArray as $k=>$v) 
{ 
    if(isset($v['importantKey']) && isset($v['otherKey'])) 
    { 
     $data[$v['importantKey']]=array('otherKey' =>$v['otherKey']); 
    } 
} 

echo "<pre />"; 
print_r($data); 
+1

根据经验,它使事情更容易使用,以保持值数组中的重要关键。所以我会在if里面做:$ data [$ v ['importantKey']] = $ v; – 2013-04-29 11:12:31

0

取决于你如何定义“干净”。这个怎么样?

$newArray = array_combine(
    array_map(function (array $i) { return $i['importantKey']; }, $oldArray), 
    array_map(function (array $i) { return array_diff_key($i, array_flip(['importantKey'])); }, $oldArray) 
); 

这不是你需要使用直线前进foreach虽然需要一些更多的迭代。

0

这是一个简单的解决方案,将整个数组除了密钥之外的数组复制到一个数组中。为什么你要PK作为数组索引呢? PHP数组不是数据库行,数组的元数据不应该是数据库数据。

$new = array(); 
foreach($old as $value) { 
    $newInner = $value; 
    unset($newInner["importantKey"]) 
    $new[$value["importantKey"]] = array($newInner); 
} 
相关问题