php - Converting multiple strings into JSON arrays -


i have multiple strings looks following: 11-16, 16-12, 14-16

i have multiple of these, , need store them in json. need store in following format:

[   {     "score_1": 11,     "score_2": 16   },   {     "score_1": 16,     "score_2": 12   },   {     "score_1": 14,     "score_2": 16   } ] 

with score_1 being first number, , score_2 being second number. how able in php?

thanks

first create array. next create object, explode string on hyphen , store intval'd first , second number in object. push object array. repeat many strings have. finally, use json_encode json-encoded string.

$arr = [];  function addstring($str, &$arr) {     $str = explode("-", $str);     $obj = new stdclass();     $obj->score_1 = intval($str[0]);     $obj->score_2 = intval($str[1]);     $arr[] = $obj; }  addstring("11-16", $arr); addstring("16-12", $arr);  echo json_encode($arr); 

output:

[{"score_1":11,"score_2":16},{"score_1":16,"score_2":12}]


edit: updated above code use intval op has integers in object in expected output.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -