1
NOTE : This is for a PHP script !

So I've been working on a program but I right now I am stuck because I can't split the data right.

I have a list with numbers just like this :

50.0.1 581 50.0.2 545 50.0.3 541 50.0.4 18 50.0.5 2 50.0.6 33 50.0.7 1 [...]

I have add that information into an ARRAY or JSON format (preferable JSON).

The main data looks like this (we take groups): 50.0.1 581 so basically I have to split 50.0.1 from 581 add it to JSON/ARRAY and then move to the next group that in our case is 50.0.2 545. (and so on)

Example JSON:

{"result": {
    "50.0.1": "581",
    "50.0.2": "545"
}}

Note : First value will always have the same format : [0-9]{2}.[0-9].[0-9] (ex : 50.0.1)

However, the second value can be 1 to 4 digit long : [0-9]{1,4}.

I am sorry if I did not make myself clear - it is quite hard to explain. Will add more example if required !

Thank you very much !

3 Answers 3

2

simply explode on the spaces, e.g.

$arr = explode(' ', $your_string);

then build a new array using each pair of elements:

$newarr = array();
for ($i = 0; $i < count($arr); $i += 2) {  // note the += 2
    $newarr[$arr[$i]] = $arr[$i+1];
}
echo json_encode($newarr);

note that this will probably trash things if any of those "key" values are duplicates.

Sign up to request clarification or add additional context in comments.

3 Comments

It seem to work well so far. I will test it with different examples and get back here to add one more comment or just make it as the accepted answer. Thank you very much !
It did not add them as separate elements : puu.sh/1tLaM. Instead it's only one big element and then :null
looks like it's tab and carriage return separated. would've been nice if you mentioned that in the original post. so basically, explode on the \r, then explode each individual bit on \t, or since it seems to basically be csv data, use fgetcsv on the original file in a loop.
0

My own working solution : /([.\d])\t(\d)/ . Will output 3 arrays. Simple combine second with third and I got what I want.

Comments

0

Another way is to use array_chunk() after explode(), and then access values in JS as item[0] and item[1] for each pair.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.