简体   繁体   中英

Fast way to rename the key of this array of associative arrays

I have this php array;

array(
    (int) 0 => array(
        'KeyName' => array(
            'id' => '1',
            'number' => '11A',
        )
    ),
    (int) 1 => array(
        'KeyName' => array(
            'id' => '2',
            'number' => '22A',
        )
    ),
    (int) 2 => array(
        'KeyName' => array(
            'id' => '16',
            'number' => '001A',
        )
    )
)

I would like to change 'KeyName' to 'NewKeyName' such that the new array becomes;

array(
    (int) 0 => array(
        'NewKeyName' => array(
            'id' => '1',
            'number' => '11A',
        )
    ),
    (int) 1 => array(
        'NewKeyName' => array(
            'id' => '2',
            'number' => '22A',
        )
    ),
    (int) 2 => array(
        'NewKeyName' => array(
            'id' => '16',
            'number' => '001A',
        )
    )
)

What is a fast way to do this?

Below is the code I tried;

foreach ($array as $key)
{
    $array[$key]['KeyName']=$array[$key]['NewKeyName'];
}

But I got some illegal offset error. Are there better ways to solve the problem?

In your code you are getting the value instead of key in $key . You have to try $array as $key => $val instead of $array as $key . Also once inside the loop just copy the value to new index and unset the existing index.

Like

foreach ($array as $key => $val)
{
    $array[$key]['NewKeyName'] = $array[$key]['KeyName'];
    unset($array[$key]['KeyName']);
}

Since you're looking to replace, just use the copy inside the foreach:

Basically you put the whole copy of the array instead of using the key:

foreach ($array as $key) {
                 // ^ this is the copy of that sub array not the key
    $array[$key]['KeyName']=$array[$key]['NewKeyName'];
}

So finally if you want in a new one:

$new_array = [];
foreach($array as $key => $value) {
                 // ^ keys goes here
    $new_array[$key]['NewKeyName'] = $value['KeyName'];
}

Or since you cannot reference keys:

foreach($array as $key => $value) {
    $array[$key]['NewKeyName'] = $value['KeyName'];
    unset($array[$key]['KeyName']);
}

Try this code, it should work:

$array2[] = array();
for ($i = 0; $i < count($array); $i++)
{
    $array2[$i]['NewKeyName'] = array_merge($array[$i]['KeyName']);
}
$array = $array2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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