如何多次将字符串分解后将字符串转换为有效的json

我一次试图爆炸更多的字符串并将结果转换为有效的json,但我无法找出方法


我正在尝试爆炸并在每次爆炸中进行foreach,但没有任何工作对我有用


$str='ID=62981155;IT=OV80419674-62981155_1_3;OD=15.4;|ID=62981157;IT=OV80419674-62981157_1_3;OD=3.1;|ID=62981159;IT=OV80419674-62981159_1_3;OD=8.13;|';



$array = explode(';|',$str);


foreach($array as $key => $val) 

{

  $v = explode(";",$val);

  foreach($v as $v1)

  {

    $v2= explode("=",$v1);

    foreach($v2 as $k => $s)

    {

    $u[] = $s;  

    }



  }

}


echo json_encode($u);

现在得到的结果:[“ ID”,“ 62981155”,“ IT”,“ OV80419674-62981155_1_3”,“ OD”,“ 15.4”,“ ID”,“ 62981157”,“ IT”,“ OV80419674-62981157_1_3” ,“ OD”,“ 3。”,“ ID”,“ 62981159”,“ IT”,“ OV80419674-62981159_1_3”,“ OD”,“ 8.13”,“”]


预期的结果是:[{“ ID”:62981155,“ IT”:“ OV80419674-62981155_1_3”,“ OD”:15.4},{“ ID”:62981157,“ IT”:“ OV80419674-62981157_1_3”,“ OD” :3.1},{“ ID”:62981159,“ IT”:“ OV80419674-62981159_1_3”,“ OD”:8.13}]]


FFIVE
浏览 159回答 3
3回答

当年话下

我将数据分为两个级别,$out即总体内容和$u每个单独的详细信息集(在每个循环中重置)。请注意,在您将其分割为的内循环上=,这将返回一个键和一个值。这用于设置关联数组,而不仅仅是将每个值添加到数组中。$array = explode(';|',$str);$array = array_filter($array);$out = [];foreach($array as $key => $val){    $u = [];    $v = explode(";",$val);    foreach($v as $v1)    {        list($key, $value) = explode("=",$v1);        $u[$key] = $value;    }    $out[] = $u;}echo json_encode($out);

Smart猫小萌

因为第二个爆炸为您提供了类似“ KEY = VALUE”的对,所以第三个爆炸已经为您提供了所需的条件:KEY和VALUE。无需循环运行,您可以使用列表一次提取两个值<?php$str='ID=62981155;IT=OV80419674-62981155_1_3;OD=15.4;|ID=62981157;IT=OV80419674-62981157_1_3;OD=3.1;|ID=62981159;IT=OV80419674-62981159_1_3;OD=8.13;|';$array = explode(';|', $str);$u = [];foreach($array as $key => $val)&nbsp;{&nbsp; if (empty($val)) {&nbsp; &nbsp; continue;&nbsp; }&nbsp; $tmp = [];&nbsp; foreach(explode(";", $val) as $v1)&nbsp; {&nbsp; &nbsp; list($k, $s) = explode("=", $v1);&nbsp; &nbsp; $tmp[$k] = $s;&nbsp;&nbsp; }&nbsp;&nbsp; $u[] = $tmp;}echo json_encode($u);此打印[{“ ID”:“ 62981155”,“ IT”:“ OV80419674-62981155_1_3”,“ OD”:“ 15.4”},{“ ID”:“ 62981157”,“ IT”:“ OV80419674-62981157_1_3”,“ OD “:” 3.1“},{” ID“:” 62981159“,” IT“:” OV80419674-62981159_1_3“,” OD“:” 8.13“}]
打开App,查看更多内容
随时随地看视频慕课网APP