1

Say I have a multidimensional, numeric zero-indexed array that looks like this:

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

What's the cleanest way to map this to the following, provided I can be sure of the uniqueness of "importantKey"

$newArray = (
    1 => array("otherKey" => "someValue"),
    4 => array("otherKey" => "someValue"),
);

This is useful when retrieving multiple rows from a database after doing a GROUP BY clause on "importantKey"

4

4 回答 4

2

尝试这个

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

    return $res;
}, array());

这够优雅吗?:)

于 2013-04-29T10:48:01.450 回答
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);
于 2013-04-29T10:47:43.433 回答
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

于 2013-04-29T10:49:56.697 回答
0

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

$new = array();
foreach($old as $value) {
    $newInner = $value;
    unset($newInner["importantKey"])
    $new[$value["importantKey"]] = array($newInner);
}
于 2013-04-29T10:51:37.650 回答