繁体   English   中英

从包含元素的键的值枚举多维PHP数组上的键的最优雅方法是什么?

[英]What's the most elegant way to enumerate keys on a multidimensional PHP array from the value of a contained element's key?

假设我有一个多维,数字零索引数组,如下所示:

$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子句后从数据库中检索多行时,这很有用

尝试这个

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

    return $res;
}, array());

这是优雅的吗? :)

$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);

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

$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但这需要更多的迭代次数。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM