2015-12-01 107 views
2

我正在构建一个流程图(非常类似于Sankey图表),但我在处理数据时遇到了一些麻烦。逗号分隔的步骤,具有相同的值的多个步骤

我从API调用中获取JSON文件。我正在使用PHP脚本将JSON输出存储在MySQL数据库中。

的问题是布局,因为它是现在:

('A, B, C, D, E, F', 123456), 
('A, B, C, D', 6543), 
('B, C', 94934), 

我需要什么(我想单独分割的每一步,但需要的价值为每一步创建TE流程图) 。

('A, B', 123456), 
('B, C', 123456), 
('C, D', 123456), 
('D, E', 123456), 
('E, F', 123456), 
('A, B', 6543), 
('B, C', 6543), 
('C, D', 6543), 
('B, C', 94934) 

JSON到数据库

$json_data = file_get_contents($CALL); 
$json_data = str_replace("'","",$json_data); 
$array = json_decode($json_data,true); 
$sql_inserts = array(); 
foreach($array['reportitems']['reportitem'][0]['rows']['r'] AS $row) 
    { 
     $sql_inserts[] = "('".$row[c][0]."','".$row[c][1]."')"; 
    }; 
$sql = 'INSERT INTO flow (flow,number) VALUES '.implode(",",$sql_inserts); 
    if (mysqli_query($conn, $sql)) { 
      echo "Ok"; 
    } else {echo "<Error" . mysqli_error($conn) ;} 
mysqli_close($conn); 



输出API调用 - JSON

{ 
    "reportitems": { 
    "@count": "1", 
    "reportitem": [ 
     { 
     "columns": { 
      "@count": "2", 
      "column": [ 
      { 
       "ctitle": "flow", 
       "type": "track", 
       "alignment": "left" 
      }, 
      { 
       "ctitle": "number", 
       "type": "integer", 
       "alignment": "right" 
      } 
      ] 
     }, 
     "title": "flow", 
     "statistics": { 
      "total": { 
      "c": [ 
       "", 
       "10813438" 
      ] 
      }, 
      "maximum": { 
      "c": [ 
       "", 
       "2482782" 
      ] 
      }, 
      "average": { 
      "c": [ 
       "", 
       "29" 
      ] 
      }, 
      "minimum": { 
      "c": [ 
       "", 
       "1" 
      ] 
      } 
     }, 
     "rows": { 
      "@count": "3", 
      "r": [ 
      { 
       "c": [ 
       "A, B, C, D, E, F", 
       "123456" 
       ] 
      }, 
      { 
       "c": [ 
       "A, B, C, D", 
       "6543" 
       ] 
      }, 
      { 
       "c": [ 
       "B, C", 
       "94934" 
       ] 
      } 
      ] 
     } 
     } 
    ] 
    } 
} 

我在哪里需要解决这一问题?将JSON输出写入MySQL数据库的脚本?或者从数据库查询sankey图表(期望分离的格式)?

回答

2

你可以试试:

foreach($array['reportitems']['reportitem'][0]['rows']['r'] AS $row) 
{ 
    // EXPLODE TO GET INDIVIDUAL CHARACTERS 
    $explodedCharac = explode(',', $row[c][0]); 
    // LOOP THROUGH EACH CHARACTER 
    foreach($explodedCharac as $key => $charac) 
    { 
     // CHECK IF THIS IS NOT THE LAST CHARACTERS IN THE EXPLODED LIST 
     if(isset($explodedCharac[$key+1])) { 
      // PREPARE ARRAY WITH CURRENT AND NEXT CHARACTER, IF THIS IS NOT THE LAST CHARACTER IN THE EXPLODED LIST 
      $sql_inserts[] = "('".$explodedCharac[$key].", ".$explodedCharac[$key+1]."','".$row[c][1]."')"; 
     } 
    } 

}; 
+0

这是伟大的东西!这总比你想象的要容易。 – Glarp

+0

非常真实。有时候,棘手的问题似乎很容易,而且很容易解决。:) –