Home > Software engineering >  How to create a JSON with PHP?
How to create a JSON with PHP?

Time:10-13

I'm looking to order data from a Json file with PHP :

    $url = 'data.json';
    $json_string = file_get_contents($url);
    $json = json_decode($json_string);
    $rows = $json->values;
    
    foreach($rows as $row) {
    
    $jsonf .= json_encode(array(
     "$row[0]" => array(
        "name" => "$row[1]",
        "value" => "$row[2]",
        "conso" => "$row[3]", 
        "ml" => "$row[4]"
     )
    ), JSON_UNESCAPED_UNICODE);
}

Unfortunately, with this method, I get a bad result:

{
    "DATA_01": {
        "name": "name_01",
        "value": "value_01",
        "conso": "conso_01",
        "ml": "ml_01"
    }
} {
    "DATA_02": {
        "name": "name_02",
        "value": "value_02",
        "conso": "conso_02",
        "ml": "ml_02"
    }
} {
    "DATA_03": {
        "name": "name_03",
        "value": "value_03",
        "conso": "conso_03",
        "ml": "ml_03"
    }
} 

I would rather get something like this:

{
    "DATA_01": {
        "name": "name_01",
        "value": "value_01",
        "conso": "conso_01",
        "ml": "ml_01"
    },
    "DATA_02": {
        "name": "name_02",
        "value": "value_02",
        "conso": "conso_02",
        "ml": "ml_02"
    },
    "DATA_03": {
        "name": "name_03",
        "value": "value_03",
        "conso": "conso_03",
        "ml": "ml_03"
    }
} 

Could someone help me solve my problem. Thank you very much for all the help you can give me.

CodePudding user response:

I am not really sure what you want to accomplish, but I think it is the following:

You get this result because you are putting the json_encode function within a for-loop. put all your detain an array, and encode it after that. Your code will become like this:

foreach($rows as $row) {
    $data[] = $row[0];
}

json_encode($data)
  • Related