Change Plain Text To JSON Array - php

I am getting the following data from a 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
Any ideas on how to turn this into a json array?
I want the data in format
"transfer_date":"2018-02-14","content":"123445585989898","count":"1"
so I can run it through a for each.
I have tried on the values but it only gets me halfway there and I can keep using find replace but there must be another way no?:
//$datatwo = str_replace('transfer_date: '"transfer_date":"',"$datatwo");

You can use regex to get not-space symbols before and after colon
$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

i'm not sure, but i guess this would work for you.
<?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);

Simpliest you could do if the there are only spaces between fields and colons as key/value separator:
$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));

Related

Array key value pair from string

I have a string
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
Need to convert this string in below format.
$utmcsr = google;
$utmcmd= organic;
$utmccn= (not set);
$utmctr= (not provided);
and more can come. I have try explode and slip function but not gives result. Please suggest.
Thanks in advance
With "Double explode" you can extract all key-value pairs from the string. First, explode on the pipe symbol, the resuting array contains strings like utmcsr=google. Iterate over this array and explode each string on the equal sign:
$result = [];
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
$arr = explode('|', $str);
foreach($arr as $str2) {
$values = explode('=', $str2);
$result[ $values[0] ] = $values[1];
}
Try this one
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
$new_array = explode('|', $str);
$result_array = array();
foreach ($new_array as $value) {
$new_arr = explode('=', $value);
$result_array[$new_arr[0]] = $new_arr[1];
}
extract($result_array);
echo $utmcsr;
echo $utmctr;
Output: google(not provided)

Convert a semicolon separated string to an array of associative arrays then json encode

I am facing some problems while converting a set of semicolon delimited strings to json.
The input string:
si;dialed_no;connect_time;duration;region;call_cost
0;918592877727;2015-08-25 18:51:01;21;India(91);0.029
1;918907777727;2015-08-25 19:04:08;220;India(91);0.232
2;918907777727;2015-08-25 19:09:50;40;India(91);0.058
3;918907777727;2015-08-25 19:10:46;69;India(91);0.087
4;919048232151;2015-08-26 13:30:24;19;India(91);0.029
5;919895842822;2015-08-26 14:23:35;423;India(91);0.435
My code:
function my_wrap($val) {
return '{"test":"' . $val. '"}';
}
$parts = explode(';', $string);
$parts = array_map('my_wrap', $parts);
$json = '[' . implode(',', $parts) . ']';
echo $json;
And the output is like:
[{"test":"dialed_no"},{"test":"connect_time"},{"test":"duration"},{"test":"region"},{"test":"call_cost 0"},{"test":"918592877727"},{"test":"2015-08-25 18:51:01"},{"test":"21"},{"test":"India(91)"},{"test":"0.029 1"},{"test":"918907777727"},{"test":"2015-08-25 19:04:08"},{"test":"220"},{"test":"India(91)"},{"test":"0.232 2"},{"test":"918907777727"},{"test":"2015-08-25 19:09:50"},{"test":"40"},{"test":"India(91)"},{"test":"0.058 3"},{"test":"918907777727"},{"test":"2015-08-25 19:10:46"},{"test":"69"},{"test":"India(91)"},{"test":"0.087 4"},{"test":"919048232151"},{"test":"2015-08-26 13:30:24"},{"test":"19"},{"test":"India(91)"},{"test":"0.029 5"},{"test":"919895842822"},{"test":"2015-08-26 14:23:35"},{"test":"423"},{"test":"India(91)"},{"test":"0.435 6"},{"test":"8801711788025"},{"test":"2015-08-30 19:29:48"},{"test":"1"},{"test":"Bangladesh(880)"},{"test":"0.029 7"},{"test":"8801711788025"},{"test":"2015-08-30 19:29:57"},{"test":"2"},{"test":"Bangladesh(880)"},{"test":"0.029 8"},{"test":"8801711788025"},{"test":"2015-08-30 19:30:07"},{"test":"2"},{"test":"Bangladesh(880)"},{"test":"0.029 9"},{"test":"8801711788025"},{"test":"2015-08-30 19:30:17"},{"test":"1"},{"test":"Bangladesh(880)"},{"test":"0.029 10"},{"test":"8801711788025"},{"test":"2015-08-30 21:24:31"},{"test":"88"},{"test":"Bangladesh(880)"},{"test":"0.087 11"},{"test":"8801833316038"},{"test":"2015-08-31 12:06:15"},{"test":"5"},{"test":"Bangladesh(880)"},{"test":"0.029 12"}]
What I want is like:
[{si:"0",dialed_no:"91xxx",connect_time:"2015-08-25 18:51:01"}, {si:"1",dialed_no:"9184sd",connect_time:"2015-08-25 18:51:01"}]
and so on...
Note: I am getting the above input string from a API URL and not from a csv file or something.
Can you try this code and see if it works as you want?
//we split the single lines
$lines = explode("\n", $string);
$linesArray = array();
//we split each line in a set of elements
foreach($lines as $line){
$linesArray[] = explode(";",$line);
}
//we use the first line of data as an array of headers
$headers = $linesArray[0];
//and remove it
unset($linesArray[0]);
$jsonArray = [];
foreach($linesArray as $l=>$ln){
foreach($ln as $k=>$part){
//we re-build an array with the right headers
$jsonArray[$l][$headers[$k]] = $part;
}
}
print json_encode($jsonArray);
What you described as the output you want is not JSON.
Don't invent your own routines when PHP already has perfectly good ones (e.g. for JSON encoding and CSV parsing).
Assuming that the data is starting in a file....
$data=array();
$y=0;
$header=fgtetcsv($file_handle, 0, ';');
while (!feof($file_handle)) {
$row=fgtetcsv($file_handle, 0, ';');
foreach ($row as $x=>$value) {
$data[$y][$header[$x]]=$value;
}
$y++;
}
print json_encode($data);
Of course this will need some tweaks to handle error conditions and possibly for datasets larger than the working memory of php.
<?php
$records = array_map(
function($e) { // 2: to each line/record apply this functions
return str_getcsv($e, ';'); // 3: split the line/record into fields
},
explode( "\n", data() ) // 1: split data into "lines"/records
);
// 4: now $records is an array of records, each being an array of fields
$fields = array_shift($records); // 5: first record contains the field names, remove from array and assign to $fields
$records = array_map(
function($e) use ($fields) { // 7: this function has access to $fields, i.e. the names of the fields
return array_combine($fields, $e); // 8: see http://docs.php.net/array_combine
},
$records // 6: apply the function above to each element, i.e. record, in $records
);
echo json_encode($records);
function data() {
return <<< eot
si;dialed_no;connect_time;duration;region;call_cost
0;918592877727;2015-08-25 18:51:01;21;India(91);0.029
1;918907777727;2015-08-25 19:04:08;220;India(91);0.232
2;918907777727;2015-08-25 19:09:50;40;India(91);0.058
3;918907777727;2015-08-25 19:10:46;69;India(91);0.087
4;919048232151;2015-08-26 13:30:24;19;India(91);0.029
5;919895842822;2015-08-26 14:23:35;423;India(91);0.435
eot;
}
While I appreciate that VolkerK is using a lot of the right functions, I find that functional syntax creates too much bloat and makes the code harder to read. Furthermore, this task can be accomplished in a single loop and therefore it should be.
Code: (Demo)
$input = <<<SSV
si;dialed_no;connect_time;duration;region;call_cost
0;918592877727;2015-08-25 18:51:01;21;India(91);0.029
1;918907777727;2015-08-25 19:04:08;220;India(91);0.232
2;918907777727;2015-08-25 19:09:50;40;India(91);0.058
3;918907777727;2015-08-25 19:10:46;69;India(91);0.087
4;919048232151;2015-08-26 13:30:24;19;India(91);0.029
5;919895842822;2015-08-26 14:23:35;423;India(91);0.435
SSV;
$lines = explode(PHP_EOL, $input);
$header = str_getcsv(array_shift($lines), ';');
foreach ($lines as $line) {
$result[] = array_combine($header, str_getcsv($line, ';'));
}
echo json_encode($result, JSON_PRETTY_PRINT);
A note to the OP, you must not manually craft a json string. Always rely on the accuracy of json_encode() -- it won't fail you.

PHP - Add value to comma based string/array

I am storing some data in my database in a comma based string like this:
value1, value2, value3, value4 etc...
This is the variables for the string:
$data["subscribers"];
I have a function which on users request can remove their value from the string or add it.
This is how I remove it:
/* Remove value from comma seperated string */
function removeFromString($str, $item) {
$parts = explode(',', $str);
while(($i = array_search($item, $parts)) !== false) {
unset($parts[$i]);
}
return implode(',', $parts);
}
$newString = removeFromString($existArr, $userdata["id"]);
So in the above example, I am removing the $userdata['id'] from the string (if it exists).
My problem is.. how can I add a value to the comma based string?
Best performance for me
function addItem($str, $item) {
return ($str != '' ? $str.',' : '').$item;
}
You can use $array[] = $var; simply do:
function addtoString($str, $item) {
$parts = explode(',', $str);
$parts[] = $item;
return implode(',', $parts);
}
$newString = addtoString($existArr, $userdata["id"]);
function addToString($str, $item) {
$parts = explode(',', $str);
array_push($parts, $str);
return implode(',', $parts);
}
$newString = addToString($existArr, $userdata["id"]);

PHP get a string into a associative array

I've got a variable going like this(in the original list there no whitespace):
http://www.iso.org/iso/list-en1-semic-3.txt
$country ="
ÅLAND ISLANDS;AX
ALBANIA;AL
ALGERIA;DZ
";
(going on and on in the same order)
I like to put this in a array going like this:
array: [Åland Islands] ==> AX
[Albania] ==> AL
[Algeria] ==> DZ
I've try to use php explode but that doesn't work, my knowledge is to basic to get it right. Who can help?
print_r(explode(';', $country));
This will get you where you're going:
$output = array();
// break it line-by-line
$lines = explode('\n', $country);
// iterate through the lines.
foreach( $lines as $line )
{
// just make sure that the line's whitespace is cleared away
$line = trim( $line );
if( $line )
{
// break the line at the semi-colon
$pieces = explode( ";", $line );
// the first piece now serves as the index.
// The second piece as the value.
$output[ $pieces[ 0 ] ] = $pieces[ 1 ];
}
}
$result = array();
$lines = explode(PHP_EOL, $country);
foreach ($lines as $line) {
$line = explode(';', $line);
$result[array_shift($line)] = array_shift($line);
}
$a = explode("\n", $country);
$result = array();
foreach($a as $line) {
list($x,$y) = explode(";", $line);
$result[$x] = $y;
}
Note: remove extra empty lines from $country or check for empty lines.

parsing a text file in php and retrieving information

I'm trying to parse a basic text file in PHP, but not sure where to begin.
The file contains info such as:
http://pastebin.com/ahqtJzH6
You'll notice that the information I need to capture is split up by new lines. Right now I'm just throwing every new line into a $applicant[] array, but I need to get rid of the preceding text in each line.
I was thinking I probably need to use regex or something to single out just the data I need. Ideas?
Thank you!
Without using regex, you can do this:
$fp = fopen('textfile.txt', 'r');
$return = array();
while ($line = fgets($fp)) {
$parts = explode(':', $line);
$key = trim($parts[0]);
unset($parts[0]);
$value = str_replace("\n", '', implode(':', $parts));
$return[$key] = trim($value);
}
print_r($return);
Would output something like:
Array (
[Applicant SSN] => 123456789
[Applicant Name] => BOB, BOB
...
)
You could use strpos to find the : character and then grab everything after that. You can use trim to get rid of extra whitespace.
$lines = file('textfile.txt');
foreach ($lines as $line) {
$p = strpos($line, ':');
if ($p!==false) {
$key = trim(substr($line, 0, $p));
$value = trim(substr($line, $p+1));
// do whatever with your key & value
}
}

Categories