将纯文本更改为JSON数组

时间:2018-02-15 20:59:29

标签: php arrays json

我从file_get_contents php://input

获取以下数据
transfer_date:2018-02-14 content:1000_102eabca374092d1e97daf0bf52e9d count:1

transfer_date:2018-02-13 content:1000_1022e2297c8e9e1a18743182e4f265 count:0

transfer_date:2018-02-13 content:1000_10254e35fda57121d48bd71693c500 count:0.5

transfer_date:2018-02-12 content:102ead3122a4c8742bff97fcc46b38 count:0.5

transfer_date:2018-02-12 content:1000_102ee58d8e12eadbce86d526607164 count:0.5

关于如何将其转换为json数组的任何想法?

我希望数据格式为

"transfer_date":"2018-02-14","content":"123445585989898","count":"1" 

所以我可以为每个人运行它。

我已经尝试了这些值,但它只让我到了一半,我可以继续使用find replace但是必须有另一种方式没有?:

//$datatwo = str_replace('transfer_date: '"transfer_date":"',"$datatwo");

3 个答案:

答案 0 :(得分:2)

您可以使用正则表达式在冒号

之前和之后获取非空格符号
$arr = array_map(function($x) {
     if (preg_match_all('/(\S+):(\S+)/',$x, $m)) {
       return array_combine($m[1], $m[2]);
     }
  }, file('php://stdin', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));

echo json_encode($arr, JSON_PRETTY_PRINT);

demo

答案 1 :(得分:0)

我不确定,但我想这对你有用。

<?php

$input = file('php://stdin', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$transfers = [];


foreach($input as $line) {
   $transfer=[];
   // break the white space between key=value so each key/value get added alone 
   $parts = explode(' ',$line);
   foreach($parts as $part) {
      // separate the key and value 
      $values=explode(':',$part); 
      $transfer[ $values[0] ] = $values[1] ?? null;
   }
   // add to the result 
   $transfers[]= $transfer;
}
// print json encoded result
echo json_encode($transfers);

答案 2 :(得分:-1)

如果字段和冒号之间只有空格作为键/值分隔符,那么你可以做到最简单:

$data = ''; //your data

$data = str_replace("\r\n", "\n", $data); //remove carriage return

$lines = array_filter(explode("\n", $data)); //split your data by new line and filter empty lines

$rows = [];

foreach ($lines as $line) {
    $fields = explode(' ', $line); //explode the content of a line by space to get all fields

    foreach ($fields as $field) {
        $fieldParts = explode(':', $field); //explode a field to get key and value

        $rows[$fieldParts[0]] = $fieldParts[1]; //assign it to your result array
    }
}

var_dump(json_encode($rows));