pat
pat

Reputation: 5797

Convert string into json

I have a string with timestamps (24h clock) and names of tv-shows, the format looks like this:

21.45 Batman 23.30 The Hour 00.20 Newsfeed 04.00 Otherfeed 21.55 Soccer: USA - Spain 23.30 The Wire

The string can be of any length, and i cannot modify the string in any way. I still want to use the string in a way that i need it as json. The string is always in the same format.

My goal is to convert the string to something like this:

{
  "shows": [
    {
        "show": "Batman",
        "time": "21.45"
    },
    {
        "show": "The Hour",
        "time": "23.30"
    },
    {
        "show": "Newsfeed",
        "time": "00.20"
    },
    {
        // etc...
    }
  ]
}

Im doing this with PHP and I really suck at regexp, its high on my learning list for 2014 :)

Upvotes: 2

Views: 107

Answers (2)

Filip Górny
Filip Górny

Reputation: 1769

<?php

$string = '21.45 Batman 23.30 The Hour 00.20 Newsfeed 04.00 Otherfeed 21.55 Soccer: USA - Spain 23.30 The Wire';

$floatPattern = '/[-+]?[0-9]*(\.[0-9]+)/';

preg_match_all($floatPattern, $string, $numbers);
$numbers = $numbers[0];

$names = preg_split($floatPattern, $string);

$result = array();

foreach ($numbers as $k => $v) {
    $result[] = array('show' => $names[$k+1], 'time' => $v);
}

echo json_encode(array('shows' => $result));

Upvotes: 2

zeflex
zeflex

Reputation: 1527

$code = '21.45 Batman 23.30 The Hour 00.20 Newsfeed 04.00 Otherfeed 21.55 Soccer: USA - Spain 23.30 The Wire';

preg_match_all('~(?P<time>\d+[.]\d+)\s*(?P<show>.*?)(?=\s*\d+[.]\d+|$)~', $code, $codeSplit);

$shows = array();
for($i = 0; $i <= count($codeSplit['time']); $i++) {
    $shows[] = array('show' => $codeSplit['show'][$i], 'time' => $codeSplit['time'][$i]);
}

$json = json_encode(array('shows' => $shows));


var_dump($json);

Upvotes: 2

Related Questions