stacky
stacky

Reputation: 108

convert an array of arrays to json

i want to convert this array as shown below

array_countries=array("20"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"7","label"=>"Tanta"),
"21"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"1000","label"=>"Other"),
"22"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"0","label"=>"All"),
"23"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"1","label"=>"Ahmedabad"));

into this format:

"3":{"Egypt":{"7":Tanta,"1000":"other"}},"80":{"India":{"0":"All","1":Ahmedabad}}

I am using PHP and not able to figure out how can i do this. I have used json_encode. but the results are not correct.I am using PHP as my language.

thanks in advance

Upvotes: 0

Views: 82

Answers (3)

Marten Koetsier
Marten Koetsier

Reputation: 3559

If I understand your requested output correctly, the following should do the trick:

$result = array();
foreach ($array_countries as $country) {
    $cntryValue = $country["cntryValue"];
    if (!array_key_exists($cntryValue, $result)) {
        $result[$cntryValue] = array();
    }
    $result[$cntryValue][$country["cntryLabel"]] = array();
    $result[$cntryValue][$country["cntryLabel"]][$country["value"]] = $country["label"];
}

echo json_encode($result) . "\n";

A little explanation: the array provided ($array_countries) is formatted differently as compared to your requested output. Therefore, it should be converted. That is what the foreach loop does. The formatted result can be converted to json using the json_encode function.

Upvotes: 0

Patrick  Safarov
Patrick Safarov

Reputation: 111

Before converting into json, you should change the array:

$array_countries_formated = array();

foreach ($array_countries as $item)
{
    $array_countries_formated[$item['cntryValue']][$item['cntryLabel']][$item['value']] = $item['label'];
}

echo $array_countries_formated = json_encode($array_countries_formated, JSON_FORCE_OBJECT);

Result:

{"3":{"Egypt":{"7":"Tanta","1000":"Other"}},"80":{"India":{"0":"All","1":"Ahmedabad"}}}

Upvotes: 1

Deenadhayalan Manoharan
Deenadhayalan Manoharan

Reputation: 5444

Try this...

<?php
$array_countries=array("20"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"7","label"=>"Tanta"),
"21"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"1000","label"=>"Other"),
"22"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"0","label"=>"All"),
"23"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"1","label"=>"Ahmedabad"));

$jsonString = json_encode($array_countries);

print_r($jsonString);
?>

Result:

{"20":{"cntryValue":"3","cntryLabel":"Egypt","value":"7","label":"Tanta"},"21":{"cntryValue":"3","cntryLabel":"Egypt","value":"1000","label":"Other"},"22":{"cntryValue":"80","cntryLabel":"India","value":"0","label":"All"},"23":{"cntryValue":"80","cntryLabel":"India","value":"1","label":"Ahmedabad"}}

Upvotes: 0

Related Questions