user2312198 user2312198 - 1 month ago 14
JSON Question

PHP - Rename repeat keys in JSON array

More info:
I forgot to mention that items like list_... are generated randomly

I have a text that I convert it to array using json

$tree = '{"list_Gentlemen":"root","list_Gold":"list_Gentlemen","list_Ladies":"root","list_Plata":"list_Ladies","list_Gold":"list_Ladies"}';


I convert it with

$tree = json_decode($tree,true);


But the thing is that when I convert it to array
echo $tree;
returns me

Array
(
[list_Gentlemen] => root
[list_Gold] => list_Ladies
[list_Ladies] => root
[list_Plata] => list_Ladies
)


I mean there's a repeat key
[list_Gold]
, and it doesn't insert the repeated key. Is there a way to rename that key?

Array
(
[list_Gentlemen] => root
[list_Gold] => list_Gentlemen
[list_Ladies] => root
[list_Plata] => list_Ladies
[list_Gold] => list_Ladies
)


Thanks for your help.

Answer

Update: You could replace the duplicate keys with some regex, but this only works if there are max 2 duplicates each key: $tree = preg_replace('/\[(\w{2,})(?=.*?\\1)\]\W*/', '[$1_2]=', $tree); this would have the following output: list[Gentlemen_2]=null&list[Gold_2]=Gentlemen&list[Ladies_2]=null&list[Plata]=Ladies&list[Gold]=Ladies

Having an Array with a duplicate key (list_Gold) is not possible, as duplicate's in PHP Arrays aren't supported. What you could do, is to parse the JSON string before decoding, and rename duplicates (if it's only this one index you could always replace the second match of list_Gold with list_Gold_2 for example).

This could look like this:

$tree1 = substr($tree, 0 , strpos($tree, 'list_Gold') + 2);
$tree2 = substr($tree, strpos($tree,'list_Gold') + 2);
$tree2 = str_replace('list_Gold', 'list_Gold_2', $tree2);
$tree = $tree1 . $tree2;
$treeArray = json_decode($tree, true);

Contents of the array above:

Array
(
    [list_Gentlemen] => root
    [list_Gold] => list_Gentlemen
    [list_Ladies] => root
    [list_Plata] => list_Ladies
    [list_Gold_2] => list_Ladies
)