davinci davinci - 6 months ago 10
PHP Question

Translate a Variable string in a more complex one in PHP

I have a string that looks like this, containing a variable number of pairs:

21.0 2016-04-12 04:06:00, 21.2 2016-04-12 04:09:00, ...


It should be translated to this:

{"date": VAR1, "value": VAR2}, {"date": VAR3,"value": VAR4},


Where the variables are filled in like this:

VAR2 = 21.0
VAR1 = 2016-04-12 04:06:00
...


Is there an efficient way to do this with PHP?

Answer

You could explode your string with comma and loop through the values, and again explode the $value using space with limit of 2.

Then simply append output in a variable.

$str = "21.0 2016-04-12 04:06:00, 21.2 2016-04-12 04:09:00";
$output = '';
foreach(explode(',', $str) as $key => $value) {
    $sp = explode(' ', trim($value), 2);
    $output .= ',{"date": ' . $sp[1] . ', "value": ' . $sp[0] . '}';
}
$output = empty($output) ? '' : substr($output, 1);
echo $output;

Example: https://eval.in/581825

Comments