Skip to content
Advertisement

Change Array Key Names with PHP

I have an array that has 4 elements with the same key names, for example:

   {
     "Word" : "ok",
     "key_example" : "32",
     "key_example" : "23",
     "key_example" : "21",
     "key_example" : "67"
    }

Is there any easy way that I can loop through this with PHP and change the key names to be:

   {
     "Word" : "ok",
     "key_example_1" : "32",
     "key_example_2" : "23",
     "key_example_3" : "21",
     "key_example_4" : "67"
    }

Advertisement

Answer

$string = '[{ "unicode" : "1f910" }, { "unicode" : "1f5e3" }, { "unicode" : "1f4a9" }]';
$array = json_decode($string);
$count = 1;
$final = array();
foreach ($array as $item) {
    $final['unicode_'.$count] = $item->unicode;
    $count++;
}
print_r($final); die;

if you want json then

$final = json_encode($final);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement