将JSON数组对象解析为PHP脚本


Parse JSON Array Objetct into PHP script

A必须将这个Json数组从Android发送到php脚本。在这种情况下,我发送了这个带有1个元素('CBECERA')的json,在我的php脚本中,我不知道如何解析。

如何从这个json重新创建整个CABECERA对象

 $_jsone_str= [ {'"CABECERA'":[{'"CustomerID'":'"1'",'"datetime'":'"'",'"fecha'":'"150303122830'",'"idadmin'":'"3'",'"idcli'":'"4'",'"msj'":'"'",'"nroped'":'"'",'"orderId'":'"1'",'"puntoVentaID'":'"AMALGAME'",'"status'":'"0'",'"total'":'"0.0'"}]}]
$json = json_decode($_jsone_str);
foreach ( $json ->CABECERA as $decode ){
   print_r($decode);
}

如何解析这个json数组我做错了什么?

我通常做的是:

  1. 我首先检查带有POST HEADERPOST的POST JSON是否存在:

    if( isset($_POST["POST"]) ) {
    }
    
  2. 我取消分配JSON文件:

    $data = $_POST["JSON"];
    $data = stripslashes($data);
    $jsonDecoded = json_decode($data);
    
  3. 然后我解析JSON数据:

    foreach ($jsonDecoded->**"object/array name"** as $object) {
    }
    

在您的情况下,"对象/数组名称"恰好是CABECERA

完整代码:

if( isset($_POST["JSON"]) ) {
    $data = $_POST["JSON"];
    $data = stripslashes($data);
    $jsonDecoded = json_decode($data);
    foreach ($jsonDecoded->**"object/array name"** as $object) {
    }
}

json数组必须是字符串。

函数json_decode($data,true)-查找第二个参数,它将在关联数组中返回解析后的json,否则它将作为对象。

    $json = "[ {'"CABECERA'":[{'"CustomerID'":'"1'",'"datetime'":'"'",'"fecha'":'"150303122830'",'"idadmin'":'"3'",'"idcli'":'"4'",'"msj'":'"'",'"nroped'":'"'",'"orderId'":'"1'",'"puntoVentaID'":'"AMALGAME'",'"status'":'"0'",'"total'":'"0.0'"}]}]";
foreach ( json_decode($json, true) as $decode ){
   print_r($decode);
}

确保要解码的JSON是字符串:

$_jsone_str= "[ {'"CABECERA'":[{'"CustomerID'":'"1'",'"datetime'":'"'",'"fecha'":'"150303122830'",'"idadmin'":'"3'",'"idcli'":'"4'",'"msj'":'"'",'"nroped'":'"'",'"orderId'":'"1'",'"puntoVentaID'":'"AMALGAME'",'"status'":'"0'",'"total'":'"0.0'"}]}]";
$json = json_decode($_jsone_str);

检查结果:

print_r($json);

称之为正确的方式:

foreach ( $json as $decode ){
   print_r($decode->CABECERA);
}