Skip to content
Advertisement

Modify array in php

This is my code for array creation

$insured_data['QuotaDtls']['Riskdtls'] = [
    "InsuredName"=> "Testone", 
];
$insured_data['Authenticate'] =   [
    'WACode' => '0000',
]; 
$insured_data['QuotaDtls'] = [
    'ProductType'=> 'Individual'
];

Output:

{
   "Authenticate": {
         "WACode": "0000",
   },
   "QuotaDtls": {
         "ProductType": "Individual",
         "Riskdtls": {
                "InsuredName": "Testone",
         }
   }
}

I want to do some modifications in this array tried many different ways but not able to do. This is done in code igniter, Please help.

{
   "Authenticate": {
       "WACode": "0000"
    },
   "QuotaDtls": {
       "ProductType": "Individual",
       "Riskdtls": [
                      {
                          "InsuredName": "Testone",
                      }
        ]
   }
}

Advertisement

Answer

You need to make Riskdtls an array further in $insured_data['QuotaDtls']['Riskdtls'] like following

$insured_data['Authenticate'] =   [
    'WACode' => '0000',
]; 
$insured_data['QuotaDtls'] = [
    'ProductType'=> 'Individual'
];
$insured_data['QuotaDtls']['Riskdtls'][] = [
    "InsuredName"=> "Testone", 
    "entry2"=> "testdata2", 
    "entry3"=> "testdata3" 
];

$json = json_encode($insured_data,JSON_PRETTY_PRINT) ; 

printf("<pre>%s</pre>", $json);

The desired output would be achieved by encoding the array to JSON format using json_encode function and the final output would be following:

{
    "Authenticate": {
        "WACode": "0000"
    },
    "QuotaDtls": {
        "ProductType": "Individual",
        "Riskdtls": [
            {
                "InsuredName": "Testone",
                "entry2": "testdata2",
                "entry3": "testdata3"
            }
        ]
    }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement