Search code examples
phparraysloopsmultidimensional-arrayassociative-array

Remove a column from each row of a 2d array and use it as the new first level key for each row


I want to rewrite this associative array and switch the level of the value of the key [unique_name] to the first level. Any ideas?

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

Desired output:

Array (
    [unique1] => Array (
        [value] => value1
        [name] => name1
    )
    [unique2] => Array (
        [value] => value2
        [name] => name2
    )
    [unique3] => Array (
        [value] => value3
        [name] => name3
    )
)

Cheers, Adnan


Solution

  • Try the following loop:

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

    You could just as easily do a hardcoded key-set within the loop, but this will have less portability if you add new indexes later on:

    foreach ($records as $record) {
        $uniques[$record['unique_name']] = array(
            'name' => $record['name'],
            'value' => $record['value']
        );
    }