2013-04-29 29 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); 
} 
相關問題