简体   繁体   中英

PHP json_encode() array

I want a json with this format :

{"dernierNumeroDEVIS":[{"numero_devis":"48"}]}

But I have this :

{"dernierNumeroDEVIS":{"numero_devis":"48"}}

My PHP :

    $array = [
        "numero_devis" => "0"
    ];
    $arrayDevis = array ('dernierNumeroDEVIS' => $array );
    echo json_encode($arrayDevis);

You need to wrap your array in an array

$array = [
    "numero_devis" => "0"
];
$arrayDevis = array ('dernierNumeroDEVIS' => [$array]);
echo json_encode($arrayDevis);

To avoid confusion perhaps it'll be easier to understand if you used standard objects and arrays in PHP as they will be the same when formatted as JSON.

$obj = new \stdClass();
$obj->numero_devis = 0;
$obj2 = new \stdClass();
$obj2->dernierNumeroDEVIS = [
    $obj,
];
echo json_encode($obj2);

I hope you need two dimensional array

$array = array("numero_devis" => "0");
$arrayDevis = array ('dernierNumeroDEVIS' => array($array) );
echo json_encode($arrayDevis);
$array = [];
$array['dernierNumeroDEVIS'][] = ['numero_devis'=>48];
echo json_encode($array);

Output:

{"dernierNumeroDEVIS":[{"numero_devis":"48"}]}

Not sure why you need it this way but here you go ...

$array = [
    array(
        "numero_devis" => "0",
     )
];
$arrayDevis = array ('dernierNumeroDEVIS' => $array );
echo json_encode($arrayDevis);

Result:

{"dernierNumeroDEVIS":[{"numero_devis":"0"}]}

Actually there is an array inside the array something like that:

$array = array(array("numero_devis"=>"0"));             
$arrayDevis = array('dernierNumeroDEVIS' => $array );
echo json_encode($arrayDevis);

Output:

{"dernierNumeroDEVIS":[{"numero_devis":"0"}]}

In case anyone else hasn't already said, you need to wrap your array inside another array, like this:

array ('dernierNumeroDEVIS' => [$array] )

Heh.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM