[英]What's the most elegant way to enumerate keys on a multidimensional PHP array from the value of a contained element's key?
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" 如果我能确定“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" 在对“importantKey”执行GROUP BY子句后从数据库中检索多行时,这很有用
Try this 尝试这个
$newArray = array_reduce($oldArray, function($res, $val) {
$res[$val['importantKey']]['otherKey'] = $val['otherKey'];
return $res;
}, array());
Is this elegant enought? 这是优雅的吗? :) :)
$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);
Depends on how you define "clean". 取决于你如何定义“干净”。 How about this? 这个怎么样?
$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)
);
This takes a few more iterations than you'd need using a straight forward foreach
though. 虽然使用直接的foreach
但这需要更多的迭代次数。
This is an easy solution to copy the entire array except the key to an array. 这是将除键之外的整个数组复制到数组的简单解决方案。 Why would you want PK as an array index anyway? 为什么要将PK作为数组索引? A PHP array isn't a database row, and metadata for the array shouldn't be database data. 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.