Search code examples
phpdictionaryforeachobject-literal

Creating a dictionary in PHP


I have the data in the variable $appLangs as :

[{"id":"1","site":"7","elemId":"navbar_title","en":"Home","de":"Zuhause","fr":"accueil"},{"id":"2","site":"7","elemId":"home_untilNextTime","en":"Until Next Time","de":"Bis zum n\u00e4chsten Mal","fr":"Jusqu'\u00e0 la prochaine fois"}]

How do i create an array which will give me result in an array as :

[{navbar_title :{
 “en” : "Home",
 “de” : "Zuhause"
}},{home_untilNextTime :{
 “en” : "Until Next Time",
 “de” : "Bis zum n\u00e4chsten Mal"
}}]

New to PHP, here' s what i tried and it gives me weird result:

$appLangs = sql_get_record('g_appLanguages', false, true);
foreach ($appLangs as $value) {             
    $json[$value["elemId"]] = (object) ['en' => $value["en"], 'de' => $value["de"]];    
    echo json_encode($json);        
}

Solution

  • You just need to decode the input and map it to your new structure. No need to cast to object or "in-itteration-json-encoding".

    E.g.:

    $input = '[{"id":"1","site":"7","elemId":"navbar_title","en":"Home","de":"Zuhause","fr":"accueil"},{"id":"2","site":"7","elemId":"home_untilNextTime","en":"Until Next Time","de":"Bis zum n\u00e4chsten Mal","fr":"Jusqu\'\u00e0 la prochaine fois"}]';
    $raw = json_decode($input, true);
    
    $output = array_map(function ($entry) {
        return [
            'en' => $entry['en'],
            'de' => $entry['de']
        ];
    }, array_column($raw, null, 'elemId'));
    
    echo json_encode([$output], JSON_PRETTY_PRINT);
    
    // [
    //     {
    //         "navbar_title": {
    //             "en": "Home",
    //             "de": "Zuhause"
    //         },
    //         "home_untilNextTime": {
    //             "en": "Until Next Time",
    //             "de": "Bis zum n\u00e4chsten Mal"
    //         }
    //     }
    // ]
    

    Demo: https://ideone.com/f3ZeTj


    Note: I don't see, why you'd want to wrap the directly usable object in an array.