Home > Mobile >  How to modify json key
How to modify json key

Time:10-14

I need some help to reorder the data in a json file.
I have these few lines :

foreach($rows as $row) {
    
    $data[] = array(
        "$row[0]" => array(
            "name" => "$row[1]",
            "value" => "$row[2]",
            "conso" => "$row[3]", 
            "ml" => "$row[4]"
        )
    );
}
$data = json_encode($data, JSON_FORCE_OBJECT);

This function allows me to obtain something like this : This function allows me to obtain something like this :

{
    "0": {
        "tata": {
            "name": "name_01",
            "value": "value_01",
            "conso": "conso_01",
            "ml": "ml_01"
        }
    },
    "1": {
        "toto": {
            "name": "name_02",
            "value": "value_02",
            "conso": "conso_02",
            "ml": "ml_02"
        }
    }
}

I would like something like that :

{
    "tata": {
        "name": "name_01",
        "value": "value_01",
        "conso": "conso_01",
        "ml": "ml_01"
    },
    "toto": {
        "name": "name_02",
        "value": "value_02",
        "conso": "conso_02",
        "ml": "ml_02"
    }
} 

CodePudding user response:

Get rid of a layer of array, and specify the key you want. You also don't need to quote all the variables like that.

foreach($rows as $row) {
    $data[$row[0]] = array(
        "name"  => $row[1],
        "value" => $row[2],
        "conso" => $row[3], 
        "ml"    => $row[4]
    );
}
$data = json_encode($data, JSON_FORCE_OBJECT);
  • Related