我想重写这个关联数组,并将键[unique_name]的值的级别切换到第一级别。有什么想法吗?
Array (
[0] => Array (
[value] => value1
[name] => name1
[unique_name] => unique1
)
[1] => Array (
[value] => value2
[name] => name2
[unique_name] => unique2
)
[2] => Array (
[value] => value3
[name] => name3
[unique_name] => unique3
)
)
所需输出:
Array (
[unique1] => Array (
[value] => value1
[name] => name1
)
[unique2] => Array (
[value] => value2
[name] => name2
)
[unique3] => Array (
[value] => value3
[name] => name3
)
)
干杯, 阿德南
尝试以下循环:
// create an array to hold the new schema
$uniques = array();
// loop over all the records
foreach ($records as $record) {
$uniques[$record['unique_name']] = $record;
// remove the unique_name entry from the new array
unset($uniques[$record['unique_name']]['unique_name']);
}
您可以轻松地在循环中执行硬编码键集,但如果稍后添加新索引,则可移植性会降低:
foreach ($records as $record) {
$uniques[$record['unique_name']] = array(
'name' => $record['name'],
'value' => $record['value']
);
}
$result = array();
foreach ($array as $entry) {
$result[$array['unique_name']] = array_diff_key($entry, array_flip(array('unique_name')));
}
foreach($array as $item){
$newarray[$item['unique_name']] = array('name' => $item['name'], 'value' => $item['value']);
}
只是为了好玩,使用带有闭包的 lambda 函数的版本:
$input = Array (
Array ("value" => "value1", "name" => "name1", "unique_name" => "unique1"),
Array ("value" => "value2", "name" => "name2", "unique_name" => "unique2"),
Array ("value" => "value3", "name" => "name3", "unique_name" => "unique3"));
function set_unique_key ($array, $key)
{
return array_reduce (
$array,
function ($res, $elem) use ($key) {
$res[$elem[$key]] = array_diff_key ($elem, array ("$key"=>''));
return $res;
},
array());
}
print_r (set_unique_key ($input, 'unique_name'));
如果您知道应删除最后一列并使用第一级密钥,则使用
array_pop()
$result = [];
foreach ($input as $row) {
$result[array_pop($row)] = $row;
}
var_export($result);
如果您正在寻求简洁的代码,那么
extract()
和 compact()
将使事情变得不那么冗长,更 D.R.Y.
$result = [];
foreach ($input as $row) {
extract($row);
$result[$unique_name] = compact(['value', 'name']);
}
var_export($result);