-2

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"
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
user1419810
  • 836
  • 1
  • 16
  • 29

3 Answers3

4
$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);
Hardiksinh Gohil
  • 160
  • 2
  • 13
0

You could try this:

$newArray = array();
$index = 1;
foreach ($array as $key => $value) {
    if (array_key_exists($key, $array) {
        $newArray[$key . "_" . $i++] = $value;
    }
}
13garth
  • 655
  • 1
  • 8
  • 22
Patrick Vogt
  • 898
  • 2
  • 14
  • 33
0

You can't do what you want because you will only replace the current array item value with each repeated key. But what you are trying to achieve is inline with the below code. Your keys have to be unique. It's how you fetch data from the array. They are your unique identifiers.

Here's an array :

array(
  "a" => "82",
  "b" => "32",
  "c" => "23",
  "d" => "21",
  "e" => "67"
);

You need to unset the array item and then you can set it in the array with the new key. (Heads Up! This is very inefficient. You should just build your array how you want it without using dupe keys.)

Here's how you append onto each key in the array :

$i = 1;
foreach ($array as $key => $value) {
  unset($array[$key]);
  $array[$key . "_" . $i] = $value;
  $i++;
}

print_r($array);

Output :

array(
    [a_1] => 82
    [b_2] => 32
    [c_3] => 23
    [d_4] => 21
    [e_5] => 67
);
13garth
  • 655
  • 1
  • 8
  • 22