重写php数组,改变键的级别

时间:2014-01-14 20:06:18

标签: php loops foreach associative-array

我想重写这个关联数组,并将键[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
    )
)

干杯, 阿德南

4 个答案:

答案 0 :(得分:3)

尝试以下循环:

// 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']
    );
}

答案 1 :(得分:1)

$result = array();

foreach ($array as $entry) {
    $result[$array['unique_name']] = array_diff_key($entry, array_flip(array('unique_name')));
}

答案 2 :(得分:0)

foreach($array as $item){
    $newarray[$item['unique_name']] = array('name' => $item['name'], 'value' => $item['value']);
}

答案 3 :(得分:0)

只是为了好玩,使用带有闭包的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'));